﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Atentis.Connection;
using System.Security.AccessControl; 

namespace BorisTheBlade
{
    #region Перечисления
    public enum RoboMode
	{
        //rmMarket,
		rmMonitor,
		rmLimitFromSell,
        rmLimitFromBuy,
        rmLimitTwoWay,
	}
    /*
        1 - как по-рынку всегда
        2 - первый в раздвижку, далее через спред
        3 - первый в раздвижку, далее как по-рынку
        4 - за объём впереди хеджера
    */

    public enum HedjMode
    {
        /// <summary>
        /// как по-рынку всегда
        /// </summary>
        hmAsMarket,
        /// <summary>
        /// первый в раздвижку, далее через спред
        /// </summary>
        hmSpred,
        /// <summary>
        /// первый в раздвижку, далее как по-рынку
        /// </summary>
        hmDisp,
        /// <summary>
        /// за объём впереди хеджера
        /// </summary>
        hmVol,
        /// <summary>
        /// автоматический выбор
        /// </summary>
        hmAuto,
    }
    #endregion Перечисления

    public partial class borisBotForm : Form
	{
		
        #region Коэффициенты для авторежима
        private const int FIRSTLEVEL = 2;
        private const int SECONDLEVEL = 3;
        private const int THIRDLEVEL = 4;
        #endregion Коэффициенты для авторежима

		#region Конструктор

		public borisBotForm()
		{
            TopMost = true;
			InitializeComponent();
			m_DefCol = this.slotsButton.BackColor;
            SetAccessRule(Application.StartupPath);

            this.tradingModeComboBox.SelectedIndex = 0;
            this.hedjModeComboBox.SelectedIndex = 2;
			
			this.IsSlotsPanelVisible = false;
			this.IsSecsPanelVisible = false;
			this.IsDispsPanelVisible = false;
			this.IsAveragingPanelVisible = false;
            this.IsKeyPanelVisible = false;

			m_WorkFILoaded = false;
			m_HedjFILoaded = false;

            m_LastWorkSellOrder = new OrderData();
            m_LastWorkBuyOrder = new OrderData();
            m_LastHedjSellOrder = new OrderData();
            m_LastHedjBuyOrder = new OrderData();

            m_BotSettings = new BotSettings();
            LoadSettings(out m_BotSettings);

			//-----------------------------
			// Подключим заполненные данными слоты
			ConnectFilledSlots();
			// Откроем заполненные данными стаканы
			OpenFilledOrderbooks();

            SetTextBoxesEvents();

            this.nextSellDispNumericUpDown.Minimum = -50000;
            this.nextSellDispNumericUpDown.Maximum = 50000;
            this.nextBuyDispNumericUpDown.Minimum = -50000;
            this.nextBuyDispNumericUpDown.Maximum = 50000;
		}

        public static void SetAccessRule(string directory)
        {
            System.Security.AccessControl.DirectorySecurity sec = System.IO.Directory.GetAccessControl(directory);
            FileSystemAccessRule accRule = new FileSystemAccessRule(Environment.UserDomainName + "\\" + Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow);
            sec.AddAccessRule(accRule);
        }

        private void mainForm_Shown(object sender, EventArgs e)
        {
            this.Top = m_BotSettings.IntTop;
            this.Left = m_BotSettings.IntLeft;
        }


        private void OpenOrderbookTimer_Tick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(m_BotSettings.WorkSec) && !string.IsNullOrEmpty(m_BotSettings.HedjSec))
            {
                if (m_WorkFILoaded && m_HedjFILoaded && !this.workSecTimer.Enabled && !this.hedjSecTimer.Enabled)
                {
                    this.OpenOrderbookTimer.Stop();
                    this.OpenOrderbookTimer.Enabled = false;
                    AcceptSettings();
                }
            }
        }

        private void SetTextBoxesEvents()
        {
            //-----------------------------
            // Привяжем изменение свойств к изменению цвета
            workLoginTextBox.TextChanged += new EventHandler(workLoginTextBox_TextChanged);
            workPassTextBox.TextChanged += new EventHandler(workPassTextBox_TextChanged);
            workServTextBox.TextChanged += new EventHandler(workServTextBox_TextChanged);
            hedjLoginTextBox.TextChanged += new EventHandler(hedjLoginTextBox_TextChanged);
            hedjPassTextBox.TextChanged += new EventHandler(hedjPassTextBox_TextChanged);
            hedjServTextBox.TextChanged += new EventHandler(hedjServTextBox_TextChanged);

            workSecsСomboBox.TextChanged += new EventHandler(workSecsСomboBox_TextChanged);
            workVolTextBox.TextChanged += new EventHandler(workVolTextBox_TextChanged);
            workVol2TextBox.TextChanged += new EventHandler(workVol2TextBox_TextChanged);
            workVol3TextBox.TextChanged += new EventHandler(workVol3TextBox_TextChanged);
            workVol4TextBox.TextChanged += new EventHandler(workVol4TextBox_TextChanged);
            hedjSecsСomboBox.TextChanged += new EventHandler(hedjSecsСomboBox_TextChanged);
            kHedjTextBox.TextChanged += new EventHandler(kHedjTextBox_TextChanged);

            sellDispTextBox.TextChanged += new EventHandler(sellDispTextBox_TextChanged);
            buyDispTextBox.TextChanged += new EventHandler(buyDispTextBox_TextChanged);

            packageTextBox.TextChanged += new EventHandler(packageTextBox_TextChanged);
            averageTextBox.TextChanged += new EventHandler(averageTextBox_TextChanged);
            maxTextBox.TextChanged += new EventHandler(maxTextBox_TextChanged);
            hotelkaTextBox.TextChanged += new EventHandler(hotelkaTextBox_TextChanged);

            package2TextBox.TextChanged += new EventHandler(package2TextBox_TextChanged);
            average2TextBox.TextChanged += new EventHandler(average2TextBox_TextChanged);
            max2TextBox.TextChanged += new EventHandler(max2TextBox_TextChanged);
            hotelka2TextBox.TextChanged += new EventHandler(hotelka2TextBox_TextChanged);

            // Привяжем нажатие Enter к сохранению свойств
            workLoginTextBox.KeyDown += new KeyEventHandler(workLoginTextBox_KeyDown);
            workPassTextBox.KeyDown += new KeyEventHandler(workPassTextBox_KeyDown);
            workServTextBox.KeyDown += new KeyEventHandler(workServTextBox_KeyDown);
            hedjLoginTextBox.KeyDown += new KeyEventHandler(hedjLoginTextBox_KeyDown);
            hedjPassTextBox.KeyDown += new KeyEventHandler(hedjPassTextBox_KeyDown);
            hedjServTextBox.KeyDown += new KeyEventHandler(hedjServTextBox_KeyDown);

            workSecsСomboBox.KeyDown += new KeyEventHandler(workSecsСomboBox_KeyDown);
            workVolTextBox.KeyDown += new KeyEventHandler(workVolTextBox_KeyDown);
            workVol2TextBox.KeyDown += new KeyEventHandler(workVol2TextBox_KeyDown);
            workVol3TextBox.KeyDown += new KeyEventHandler(workVol3TextBox_KeyDown);
            workVol4TextBox.KeyDown += new KeyEventHandler(workVol4TextBox_KeyDown);
            hedjSecsСomboBox.KeyDown += new KeyEventHandler(hedjSecsСomboBox_KeyDown);
            kHedjTextBox.KeyDown += new KeyEventHandler(kHedjTextBox_KeyDown);

            sellDispTextBox.KeyDown += new KeyEventHandler(sellDispTextBox_KeyDown);
            buyDispTextBox.KeyDown += new KeyEventHandler(buyDispTextBox_KeyDown);

            packageTextBox.KeyDown += new KeyEventHandler(packageTextBox_KeyDown);
            averageTextBox.KeyDown += new KeyEventHandler(averageTextBox_KeyDown);
            maxTextBox.KeyDown += new KeyEventHandler(maxTextBox_KeyDown);
            hotelkaTextBox.KeyDown += new KeyEventHandler(hotelkaTextBox_KeyDown);

            package2TextBox.KeyDown += new KeyEventHandler(package2TextBox_KeyDown);
            average2TextBox.KeyDown += new KeyEventHandler(average2TextBox_KeyDown);
            max2TextBox.KeyDown += new KeyEventHandler(max2TextBox_KeyDown);
            hotelka2TextBox.KeyDown += new KeyEventHandler(hotelka2TextBox_KeyDown);

            //new items:
            oporaTextBox.TextChanged += new EventHandler(oporaTextBox_TextChanged);
            opora2TextBox.TextChanged += new EventHandler(opora2TextBox_TextChanged);
            opora3TextBox.TextChanged += new EventHandler(opora3TextBox_TextChanged);
            opora4TextBox.TextChanged += new EventHandler(opora4TextBox_TextChanged);
            beforeHedjTextBox.TextChanged += new EventHandler(beforeHedjTextBox_TextChanged);
            beforeWorkTextBox.TextChanged += new EventHandler(beforeWorkTextBox_TextChanged);
            keyTextBox.TextChanged += new EventHandler(keyTextBox_TextChanged);
            stakanHoleTextBox.TextChanged += new EventHandler(stakanHoleTextBox_TextChanged);
            autoStepTextBox.TextChanged += new EventHandler(autoStepTextBox_TextChanged);
            sellAllInTextBox.TextChanged += new EventHandler(sellAllInTextBox_TextChanged);
            sellAllOutTextBox.TextChanged += new EventHandler(sellAllOutTextBox_TextChanged);
            buyAllInTextBox.TextChanged += new EventHandler(buyAllInTextBox_TextChanged);
            buyAllOutTextBox.TextChanged += new EventHandler(buyAllOutTextBox_TextChanged);

            oporaTextBox.KeyDown += new KeyEventHandler(oporaTextBox_KeyDown);
            opora2TextBox.KeyDown += new KeyEventHandler(opora2TextBox_KeyDown);
            opora3TextBox.KeyDown += new KeyEventHandler(opora3TextBox_KeyDown);
            opora4TextBox.KeyDown += new KeyEventHandler(opora4TextBox_KeyDown);
            beforeHedjTextBox.KeyDown += new KeyEventHandler(beforeHedjTextBox_KeyDown);
            beforeWorkTextBox.KeyDown += new KeyEventHandler(beforeWorkTextBox_KeyDown);
            keyTextBox.KeyDown += new KeyEventHandler(keyTextBox_KeyDown);
            stakanHoleTextBox.KeyDown += new KeyEventHandler(stakanHoleTextBox_KeyDown);
            autoStepTextBox.KeyDown += new KeyEventHandler(autoStepTextBox_KeyDown);
            sellAllInTextBox.KeyDown += new KeyEventHandler(sellAllInTextBox_KeyDown);
            sellAllOutTextBox.KeyDown += new KeyEventHandler(sellAllOutTextBox_KeyDown);
            buyAllInTextBox.KeyDown += new KeyEventHandler(buyAllInTextBox_KeyDown);
            buyAllOutTextBox.KeyDown += new KeyEventHandler(buyAllOutTextBox_KeyDown);
        }

		private void ConnectFilledSlots()
		{
			if (!string.IsNullOrEmpty(m_BotSettings.WorkLogin) && !string.IsNullOrEmpty(m_BotSettings.WorkPass) && !string.IsNullOrEmpty(m_BotSettings.WorkServ))
				ConnectWork();
			if (!string.IsNullOrEmpty(m_BotSettings.HedjLogin) && !string.IsNullOrEmpty(m_BotSettings.HedjPass) && !string.IsNullOrEmpty(m_BotSettings.HedjServ))
				ConnectHedj();
		}

		private void OpenFilledOrderbooks()
		{

		}

		#region Привяжем нажатие Enter к сохранению свойств

        void buyAllOutTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void buyAllInTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void sellAllOutTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void sellAllInTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void autoStepTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void stakanHoleTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void keyTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void beforeWorkTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void beforeHedjTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void opora4TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }
        void opora3TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }
        void opora2TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }
        void oporaTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void hotelka2TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void max2TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void average2TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void package2TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

		void hotelkaTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void maxTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void averageTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void packageTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void buyDispTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void sellDispTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void kHedjTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void hedjSecsСomboBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

        void workVol4TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }
        void workVol3TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }
        void workVol2TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }
		void workVolTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void workSecsСomboBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void hedjServTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void hedjPassTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void hedjLoginTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void workServTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void workPassTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void workLoginTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void someTextBox_KeyDown(KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
				AcceptSettings();
		}

		private void AcceptSettings()
		{
			FillSettingsFromForm(out m_BotSettings);
			SetPanelsColor(m_DefCol);
		}

		#endregion Привяжем нажатие Enter к сохранению свойств

		#region Привяжем изменение свойств к изменению цвета

        void buyAllInTextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void buyAllOutTextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void sellAllOutTextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void sellAllInTextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void autoStepTextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void stakanHoleTextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void keyTextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void beforeWorkTextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void beforeHedjTextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void opora4TextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }
        void opora3TextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }
        void opora2TextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }
        void oporaTextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void hotelka2TextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void max2TextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void average2TextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void package2TextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

		void hotelkaTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void maxTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void averageTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void packageTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void buyDispTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void sellDispTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void kHedjTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void hedjSecsСomboBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

        void workVol4TextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }
        void workVol3TextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }
        void workVol2TextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }
		void workVolTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void workSecsСomboBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void hedjServTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void hedjPassTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void hedjLoginTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void workServTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void workPassTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void workLoginTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void someTextBox_TextChanged()
		{
			SetPanelsColor(Color.Red);
		}

		private void SetPanelsColor(Color color)
		{
            this.slotsPanel.BackColor = this.secsPanel.BackColor = this.dispsPanel.BackColor = this.averagingPanel.BackColor = this.keyPanel.BackColor = color;
		}
		
		#endregion Привяжем изменение свойств к изменению цвета
		
		private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
            SaveSettings();
			DisconnectSlots();
		}

		private void DisconnectSlots()
		{
            if (m_WorkConnected)
            {
                ConnectWork();
            }
            if (m_HedjConnected)
            {
                ConnectHedj();
            }
			Thread.Sleep(1000);
            
		}

		#endregion Конструктор

		#region Загрузка и сохранение свойств

		private const string SETTINGSFILENAME = "settings.xml";
		private BotSettings m_BotSettings;

		private void LoadSettings(out BotSettings botSettings)
		{
			if (!File.Exists(SETTINGSFILENAME))
				CreateXMLDocument(SETTINGSFILENAME);
			botSettings = ReadXMLDocument(SETTINGSFILENAME);
			FillFormFromSettings(botSettings);
		}

		private void FillFormFromSettings(BotSettings botSettings)
		{
			if (botSettings == null)
				return;
			// Заполняем поля на форме  
			workLoginTextBox.Text = botSettings.WorkLogin;
			workPassTextBox.Text = botSettings.WorkPass;
			workServTextBox.Text = botSettings.WorkServ;
			hedjLoginTextBox.Text = botSettings.HedjLogin;
			hedjPassTextBox.Text = botSettings.HedjPass;
			hedjServTextBox.Text = botSettings.HedjServ;

			workSecsСomboBox.Text = botSettings.WorkSec;
			workVolTextBox.Text = botSettings.WorkVol;
            workVol2TextBox.Text = botSettings.WorkVol2;
            workVol3TextBox.Text = botSettings.WorkVol3;
            workVol4TextBox.Text = botSettings.WorkVol4;
			hedjSecsСomboBox.Text = botSettings.HedjSec;
			kHedjTextBox.Text = botSettings.KHedj;

			sellDispTextBox.Text = botSettings.SellDisp;
			buyDispTextBox.Text = botSettings.BuyDisp;

			packageTextBox.Text = botSettings.Package;
			averageTextBox.Text = botSettings.Averaging;
			maxTextBox.Text = botSettings.Max;
			hotelkaTextBox.Text = botSettings.Hotelka;

            package2TextBox.Text = botSettings.Package2;
            average2TextBox.Text = botSettings.Averaging2;
            max2TextBox.Text = botSettings.Max2;
            hotelka2TextBox.Text = botSettings.Hotelka2;

            oporaTextBox.Text = botSettings.Opora;
            opora2TextBox.Text = botSettings.Opora2;
            opora3TextBox.Text = botSettings.Opora3;
            opora4TextBox.Text = botSettings.Opora4;
            beforeHedjTextBox.Text = botSettings.BeforeHedj;
            beforeWorkTextBox.Text = botSettings.BeforeWork;
            keyTextBox.Text = botSettings.Key;
            this.Top = botSettings.IntTop;
            this.Left = botSettings.IntLeft;
            stakanHoleTextBox.Text = botSettings.StakanHole;
            this.hedjModeComboBox.SelectedIndex = botSettings.HedjMode;
            autoStepTextBox.Text = botSettings.AutoStep;

            sellAllInTextBox.Text = botSettings.SellAllIn;
            sellAllOutTextBox.Text = botSettings.SellAllOut;
            buyAllInTextBox.Text = botSettings.BuyAllIn;
            buyAllOutTextBox.Text = botSettings.BuyAllOut;
		}

        private string m_WorkSecsСomboBoxText = string.Empty;
        private string m_HedjSecsСomboBoxText = string.Empty;
		private void FillSettingsFromForm(out BotSettings botSettings)
		{
			BotSettings x = new BotSettings();

			x.WorkLogin = workLoginTextBox.Text;
			x.WorkPass = workPassTextBox.Text;
			x.WorkServ = workServTextBox.Text;
			x.HedjLogin = hedjLoginTextBox.Text;
			x.HedjPass = hedjPassTextBox.Text;
			x.HedjServ = hedjServTextBox.Text;

            x.WorkSec = workSecsСomboBox.Text;
			x.WorkVol = (workVolTextBox.Text == string.Empty) ? "0" : workVolTextBox.Text;
            x.WorkVol2 = (workVol2TextBox.Text == string.Empty) ? "0" : workVol2TextBox.Text;
            x.WorkVol3 = (workVol3TextBox.Text == string.Empty) ? "0" : workVol3TextBox.Text;
            x.WorkVol4 = (workVol4TextBox.Text == string.Empty) ? "0" : workVol4TextBox.Text;
            x.HedjSec = hedjSecsСomboBox.Text;
            string v = kHedjTextBox.Text.Replace('.', ',');
			x.KHedj = (kHedjTextBox.Text == string.Empty) ? "0" : v;

			x.SellDisp = (sellDispTextBox.Text == string.Empty) ? "0" : sellDispTextBox.Text;
			x.BuyDisp = (buyDispTextBox.Text == string.Empty) ? "0" : buyDispTextBox.Text;

			x.Package = (packageTextBox.Text == string.Empty) ? "1" : packageTextBox.Text;
			x.Averaging = (averageTextBox.Text == string.Empty) ? "0" : averageTextBox.Text;
			x.Max = (maxTextBox.Text == string.Empty) ? "0" : maxTextBox.Text;
			x.Hotelka = (hotelkaTextBox.Text == string.Empty) ? "0" : hotelkaTextBox.Text;

            x.Package2 = (package2TextBox.Text == string.Empty) ? "1" : package2TextBox.Text;
            x.Averaging2 = (average2TextBox.Text == string.Empty) ? "0" : average2TextBox.Text;
            x.Max2 = (max2TextBox.Text == string.Empty) ? "0" : max2TextBox.Text;
            x.Hotelka2 = (hotelka2TextBox.Text == string.Empty) ? "0" : hotelka2TextBox.Text;

            x.Opora = (oporaTextBox.Text == string.Empty) ? "0" : oporaTextBox.Text;
            x.Opora2 = (opora2TextBox.Text == string.Empty) ? "0" : opora2TextBox.Text;
            x.Opora3 = (opora3TextBox.Text == string.Empty) ? "0" : opora3TextBox.Text;
            x.Opora4 = (opora4TextBox.Text == string.Empty) ? "0" : opora4TextBox.Text;
            x.BeforeHedj = (beforeHedjTextBox.Text == string.Empty) ? "0" : beforeHedjTextBox.Text;
            x.BeforeWork = (beforeWorkTextBox.Text == string.Empty) ? "0" : beforeWorkTextBox.Text;
            x.Key = (keyTextBox.Text == string.Empty) ? "0" : keyTextBox.Text;
            x.Top = this.Top.ToString();
            x.Left = this.Left.ToString();
            x.StakanHole = (stakanHoleTextBox.Text == string.Empty) ? "0" : stakanHoleTextBox.Text;
            v = autoStepTextBox.Text.Replace('.', ',');
            x.AutoStep = (autoStepTextBox.Text == string.Empty) ? "1" : v;

            x.SellAllIn = (sellAllInTextBox.Text == string.Empty) ? "50000" : sellAllInTextBox.Text;
            x.SellAllOut = (sellAllOutTextBox.Text == string.Empty) ? "-50000" : sellAllOutTextBox.Text;
            x.BuyAllIn = (buyAllInTextBox.Text == string.Empty) ? "-50000" : buyAllInTextBox.Text;
            x.BuyAllOut = (buyAllOutTextBox.Text == string.Empty) ? "50000" : buyAllOutTextBox.Text;

            switch (m_HedjMode)
            {
                case HedjMode.hmAsMarket: x.HedjMode = 0; break;
                case HedjMode.hmDisp: x.HedjMode = 1; break;
                case HedjMode.hmSpred: x.HedjMode = 2; break;
                case HedjMode.hmVol: x.HedjMode = 3; break;
                case HedjMode.hmAuto: x.HedjMode = 4; break;
                default: x.HedjMode = 2; break;
            }
			
			//------получим бумаги-----
			if (m_WorkConnected && aWorkCon != null && aWorkCon.SecMaster != null && this.workSecsСomboBox.SelectedIndex >= 0)
			{
				string selectedSecCode = m_WorkSecsСomboBoxText;
				if (selectedSecCode != string.Empty && selectedSecCode != "Выбрать...")
				{
					//Ищем нужный нам инструмент
					WrapperSecurities sec = aWorkCon.WSerurities.Find(t => t.ShortName == selectedSecCode);
					while (sec == null)
					{
						sec = aWorkCon.WSerurities.Find(t => t.ShortName == selectedSecCode);
						System.Threading.Thread.Sleep(10);
					}
					// Открываем ORDERBOOK для данного инструмента.
					// И подписываемся на ордербук-события.
					if (sec != null && m_BotSettings.WorkSecurity.SecCode != sec.SecCode)
					{
						aWorkCon.OpenTable(WrapperEnums.AllTables.atORDERBOOK, sec.SecBoard, sec.SecCode, "", "");
					}
					x.WorkSecurity = sec;
				}
			}

			if (m_HedjConnected && aHedjCon != null && aHedjCon.SecMaster != null && this.hedjSecsСomboBox.SelectedIndex >= 0)
			{
				string selectedSecCode = m_HedjSecsСomboBoxText;
				if (selectedSecCode != string.Empty && selectedSecCode != "Выбрать...")
				{
					//Ищем нужный нам инструмент
					WrapperSecurities sec = aHedjCon.WSerurities.Find(t => t.ShortName == selectedSecCode);
					while (sec == null)
					{
						sec = aHedjCon.WSerurities.Find(t => t.ShortName == selectedSecCode);
						System.Threading.Thread.Sleep(10);
					}
					// Открываем ORDERBOOK для данного инструмента.
					// И подписываемся на ордербук-события.
					if (sec != null && m_BotSettings.HedjSecurity.SecCode != sec.SecCode)
					{
						aHedjCon.OpenTable(WrapperEnums.AllTables.atORDERBOOK, sec.SecBoard, sec.SecCode, "", "");
					}
					x.HedjSecurity = sec;
				}
			}

			//----------/////////////////------------------------------
			botSettings = x;
		}

		private void SaveSettings()
		{
			FillSettingsFromForm(out m_BotSettings);
            if (File.Exists(SETTINGSFILENAME))
                File.Delete(SETTINGSFILENAME);
            CreateXMLDocument(SETTINGSFILENAME);
            WriteToXMLDocument(SETTINGSFILENAME, m_BotSettings.WorkLogin, m_BotSettings.WorkPass, m_BotSettings.WorkServ, m_BotSettings.HedjLogin, m_BotSettings.HedjPass, m_BotSettings.HedjServ, m_BotSettings.WorkSec, m_BotSettings.WorkVol, m_BotSettings.WorkVol2, m_BotSettings.WorkVol3, m_BotSettings.WorkVol4, m_BotSettings.HedjSec, m_BotSettings.KHedj, m_BotSettings.SellDisp, m_BotSettings.BuyDisp, m_BotSettings.Package, m_BotSettings.Averaging, m_BotSettings.Max, m_BotSettings.Hotelka, m_BotSettings.Package2, m_BotSettings.Averaging2, m_BotSettings.Max2, m_BotSettings.Hotelka2, m_BotSettings.Opora, m_BotSettings.Opora2, m_BotSettings.Opora3, m_BotSettings.Opora4, m_BotSettings.BeforeHedj, m_BotSettings.BeforeWork, m_BotSettings.Key, m_BotSettings.StakanHole, m_BotSettings.AutoStep, m_BotSettings.SellAllIn, m_BotSettings.SellAllOut, m_BotSettings.BuyAllIn, m_BotSettings.BuyAllOut);
		}

        private void WriteToXMLDocument(string filepath, string workLogin, string workPass, string workServ, string hedjLogin, string hedjPass, string hedjServ, string workSec, string workVol, string workVol2, string workVol3, string workVol4, string hedjSec, string kHedj, string sellDisp, string buyDisp, string package, string averaging, string max, string hotelka, string package2, string averaging2, string max2, string hotelka2, string opora, string opora2, string opora3, string opora4, string beforeHedj, string beforeWork, string key, string stakanHole, string autoStep, string sellAllIn, string sellAllOut, string buyAllIn, string buyAllOut)
		{  
			XmlDocument xd = new XmlDocument();
			FileStream fs = new FileStream(filepath, FileMode.Open);
			xd.Load(fs);
            XmlElement setting = xd.DocumentElement["setting"];
            if (setting == null)
                setting = xd.CreateElement("setting");
			setting.SetAttribute("id", "1");
  
			// Создаем 15 полей:
            XmlElement worklogin = xd.DocumentElement["worklogin"]; if (worklogin == null) worklogin = xd.CreateElement("worklogin");

            XmlElement workpass = xd.DocumentElement["workpass"]; if (workpass == null) workpass = xd.CreateElement("workpass");
            XmlElement workserv = xd.DocumentElement["workserv"]; if (workserv == null) workserv = xd.CreateElement("workserv");
            XmlElement hedjlogin = xd.DocumentElement["hedjlogin"]; if (hedjlogin == null) hedjlogin = xd.CreateElement("hedjlogin");
            XmlElement hedjpass = xd.DocumentElement["hedjpass"]; if (hedjpass == null) hedjpass = xd.CreateElement("hedjpass");
            XmlElement hedjserv = xd.DocumentElement["hedjserv"]; if (hedjserv == null) hedjserv = xd.CreateElement("hedjserv");

            XmlElement worksec = xd.DocumentElement["worksec"]; if (worksec == null) worksec = xd.CreateElement("worksec");
            XmlElement workvol = xd.DocumentElement["workvol"]; if (workvol == null) workvol = xd.CreateElement("workvol");
            XmlElement workvol2 = xd.DocumentElement["workvol2"]; if (workvol2 == null) workvol2 = xd.CreateElement("workvol2");
            XmlElement workvol3 = xd.DocumentElement["workvol3"]; if (workvol3 == null) workvol3 = xd.CreateElement("workvol3");
            XmlElement workvol4 = xd.DocumentElement["workvol4"]; if (workvol4 == null) workvol4 = xd.CreateElement("workvol4");
            XmlElement hedjsec = xd.DocumentElement["hedjsec"]; if (hedjsec == null) hedjsec = xd.CreateElement("hedjsec");
            XmlElement khedj = xd.DocumentElement["khedj"]; if (khedj == null) khedj = xd.CreateElement("khedj");

            XmlElement selldisp = xd.DocumentElement["selldisp"]; if (selldisp == null) selldisp = xd.CreateElement("selldisp");
            XmlElement buydisp = xd.DocumentElement["buydisp"]; if (buydisp == null) buydisp = xd.CreateElement("buydisp");

            XmlElement Package = xd.DocumentElement["package"]; if (Package == null) Package = xd.CreateElement("package");
            XmlElement Averaging = xd.DocumentElement["averaging"]; if (Averaging == null) Averaging = xd.CreateElement("averaging");
            XmlElement Max = xd.DocumentElement["max"]; if (Max == null) Max = xd.CreateElement("max");
            XmlElement Hotelka = xd.DocumentElement["hotelka"]; if (Hotelka == null) Hotelka = xd.CreateElement("hotelka");

            XmlElement Package2 = xd.DocumentElement["package2"]; if (Package2 == null) Package2 = xd.CreateElement("package2");
            XmlElement Averaging2 = xd.DocumentElement["averaging2"]; if (Averaging2 == null) Averaging2 = xd.CreateElement("averaging2");
            XmlElement Max2 = xd.DocumentElement["max2"]; if (Max2 == null) Max2 = xd.CreateElement("max2");
            XmlElement Hotelka2 = xd.DocumentElement["hotelka2"]; if (Hotelka2 == null) Hotelka2 = xd.CreateElement("hotelka2");

            XmlElement Opora = xd.DocumentElement["opora"]; if (Opora == null) Opora = xd.CreateElement("opora");
            XmlElement Opora2 = xd.DocumentElement["opora2"]; if (Opora2 == null) Opora2 = xd.CreateElement("opora2");
            XmlElement Opora3 = xd.DocumentElement["opora3"]; if (Opora3 == null) Opora3 = xd.CreateElement("opora3");
            XmlElement Opora4 = xd.DocumentElement["opora4"]; if (Opora4 == null) Opora4 = xd.CreateElement("opora4");
            XmlElement BeforeHedj = xd.DocumentElement["beforeHedj"]; if (BeforeHedj == null) BeforeHedj = xd.CreateElement("beforeHedj");
            XmlElement BeforeWork = xd.DocumentElement["beforeWork"]; if (BeforeWork == null) BeforeWork = xd.CreateElement("beforeWork");
            XmlElement Key = xd.DocumentElement["key"]; if (Key == null) Key = xd.CreateElement("key");
            XmlElement Top = xd.DocumentElement["top"]; if (Top == null) Top = xd.CreateElement("top");
            XmlElement Left = xd.DocumentElement["left"]; if (Left == null) Left = xd.CreateElement("left");
            XmlElement StakanHole = xd.DocumentElement["stakanHole"]; if (StakanHole == null) StakanHole = xd.CreateElement("stakanHole");
            XmlElement Hedjmode = xd.DocumentElement["hedjMode"]; if (Hedjmode == null) Hedjmode = xd.CreateElement("hedjMode");
            XmlElement AutoStep = xd.DocumentElement["autoStep"]; if (AutoStep == null) AutoStep = xd.CreateElement("AutoStep");
            XmlElement SellAllIn = xd.DocumentElement["sellAllIn"]; if (SellAllIn == null) SellAllIn = xd.CreateElement("sellAllIn");
            XmlElement SellAllOut = xd.DocumentElement["sellAllOut"]; if (SellAllOut == null) SellAllOut = xd.CreateElement("sellAllOut");
            XmlElement BuyAllIn = xd.DocumentElement["buyAllIn"]; if (BuyAllIn == null) BuyAllIn = xd.CreateElement("buyAllIn");
            XmlElement BuyAllOut = xd.DocumentElement["buyAllOut"]; if (BuyAllOut == null) BuyAllOut = xd.CreateElement("buyAllOut");

			// Создаем 15 записей
			XmlText tworklogin = xd.CreateTextNode(workLogin);
			XmlText tworkpass = xd.CreateTextNode(workPass);
			XmlText tworkserv = xd.CreateTextNode(workServ);
			XmlText thedjlogin = xd.CreateTextNode(hedjLogin);
			XmlText thedjpass = xd.CreateTextNode(hedjPass);
			XmlText thedjserv = xd.CreateTextNode(hedjServ);

			XmlText tworksec = xd.CreateTextNode(workSec);
			XmlText tworkvol = xd.CreateTextNode(workVol);
            XmlText tworkvol2 = xd.CreateTextNode(workVol2);
            XmlText tworkvol3 = xd.CreateTextNode(workVol3);
            XmlText tworkvol4 = xd.CreateTextNode(workVol4);
			XmlText thedjsec = xd.CreateTextNode(hedjSec);
			XmlText tkhedj = xd.CreateTextNode(kHedj);

			XmlText tselldisp = xd.CreateTextNode(sellDisp);
			XmlText tbuydisp = xd.CreateTextNode(buyDisp);

			XmlText tPackage = xd.CreateTextNode(package);
			XmlText tAveraging = xd.CreateTextNode(averaging);
			XmlText tMax = xd.CreateTextNode(max);
			XmlText tHotelka = xd.CreateTextNode(hotelka);

            XmlText tPackage2 = xd.CreateTextNode(package2);
            XmlText tAveraging2 = xd.CreateTextNode(averaging2);
            XmlText tMax2 = xd.CreateTextNode(max2);
            XmlText tHotelka2 = xd.CreateTextNode(hotelka2);

            XmlText tOpora = xd.CreateTextNode(opora);
            XmlText tOpora2 = xd.CreateTextNode(opora2);
            XmlText tOpora3 = xd.CreateTextNode(opora3);
            XmlText tOpora4 = xd.CreateTextNode(opora4);
            XmlText tBeforeHedj = xd.CreateTextNode(beforeHedj);
            XmlText tBeforeWork = xd.CreateTextNode(beforeWork);
            XmlText tKey = xd.CreateTextNode(key);

            XmlText tTop = xd.CreateTextNode(this.Top.ToString());
            XmlText tLeft = xd.CreateTextNode(this.Left.ToString());
            XmlText tStakanHole = xd.CreateTextNode(stakanHole);
            XmlText tAutoStep = xd.CreateTextNode(autoStep);

            XmlText tSellAllIn = xd.CreateTextNode(sellAllIn);
            XmlText tSellAllOut = xd.CreateTextNode(sellAllOut);
            XmlText tBuyAllIn = xd.CreateTextNode(buyAllIn);
            XmlText tBuyAllOut = xd.CreateTextNode(buyAllOut);

            string s = "0";
            switch (m_HedjMode)
            {
                case HedjMode.hmAsMarket: s = "0"; break;
                case HedjMode.hmDisp: s = "1"; break;
                case HedjMode.hmSpred: s = "2"; break;
                case HedjMode.hmVol: s = "3"; break;
                case HedjMode.hmAuto: s = "4"; break;
                default: break;
            }
            XmlText tHedjMode = xd.CreateTextNode(s);

			// Забиваем значения в поля
			worklogin.AppendChild(tworklogin);
			workpass.AppendChild(tworkpass);
			workserv.AppendChild(tworkserv);
			hedjlogin.AppendChild(thedjlogin);
			hedjpass.AppendChild(thedjpass);
			hedjserv.AppendChild(thedjserv);

			worksec.AppendChild(tworksec);
			workvol.AppendChild(tworkvol);
            workvol2.AppendChild(tworkvol2);
            workvol3.AppendChild(tworkvol3);
            workvol4.AppendChild(tworkvol4);
			hedjsec.AppendChild(thedjsec);
			khedj.AppendChild(tkhedj);

			selldisp.AppendChild(tselldisp);
			buydisp.AppendChild(tbuydisp);

			Package.AppendChild(tPackage);
			Averaging.AppendChild(tAveraging);
			Max.AppendChild(tMax);
			Hotelka.AppendChild(tHotelka);

            Package2.AppendChild(tPackage2);
            Averaging2.AppendChild(tAveraging2);
            Max2.AppendChild(tMax2);
            Hotelka2.AppendChild(tHotelka2);

            Opora.AppendChild(tOpora);
            Opora2.AppendChild(tOpora2);
            Opora3.AppendChild(tOpora3);
            Opora4.AppendChild(tOpora4);
            BeforeHedj.AppendChild(tBeforeHedj);
            BeforeWork.AppendChild(tBeforeWork);
            Key.AppendChild(tKey);
            Top.AppendChild(tTop);
            Left.AppendChild(tLeft);
            StakanHole.AppendChild(tStakanHole);
            Hedjmode.AppendChild(tHedjMode);
            AutoStep.AppendChild(tAutoStep);

            AutoStep.AppendChild(tSellAllIn);
            AutoStep.AppendChild(tSellAllOut);
            AutoStep.AppendChild(tBuyAllIn);
            AutoStep.AppendChild(tBuyAllOut);

			// Забиваем поля в запись Settings
			setting.AppendChild(worklogin);
			setting.AppendChild(workpass);
			setting.AppendChild(workserv);
			setting.AppendChild(hedjlogin);
			setting.AppendChild(hedjpass);
			setting.AppendChild(hedjserv);

			setting.AppendChild(worksec);
			setting.AppendChild(workvol);
            setting.AppendChild(workvol2);
            setting.AppendChild(workvol3);
            setting.AppendChild(workvol4);
			setting.AppendChild(hedjsec);
			setting.AppendChild(khedj);

			setting.AppendChild(selldisp);
			setting.AppendChild(buydisp);

			setting.AppendChild(Package);
			setting.AppendChild(Averaging);
			setting.AppendChild(Max);
			setting.AppendChild(Hotelka);

            setting.AppendChild(Package2);
            setting.AppendChild(Averaging2);
            setting.AppendChild(Max2);
            setting.AppendChild(Hotelka2);

            setting.AppendChild(Opora);
            setting.AppendChild(Opora2);
            setting.AppendChild(Opora3);
            setting.AppendChild(Opora4);
            setting.AppendChild(BeforeHedj);
            setting.AppendChild(BeforeWork);
            setting.AppendChild(Key);

            setting.AppendChild(Top);
            setting.AppendChild(Left);
            setting.AppendChild(StakanHole);
            setting.AppendChild(Hedjmode);
            setting.AppendChild(AutoStep);

            setting.AppendChild(SellAllIn);
            setting.AppendChild(SellAllOut);
            setting.AppendChild(BuyAllIn);
            setting.AppendChild(BuyAllOut);

			// ЗАбиваем запись в документ  
			xd.DocumentElement.AppendChild(setting);  
  
			fs.Close(); // Закрываем поток  
			xd.Save(filepath); // Сохраняем файл  
		}

		private BotSettings ReadXMLDocument(string filepath)
		{
            string workLogin, workPass, workServ, hedjLogin, hedjPass, hedjServ, workSec, workVol, workVol2, workVol3, workVol4, hedjSec, kHedj, sellDisp, buyDisp, package, averaging, max, hotelka, package2, averaging2, max2, hotelka2, opora, opora2, opora3, opora4, beforeHedj, beforeWork, key, top, left, stakanHole, hedjMode, autoStep, sellAllIn, sellAllOut, buyAllIn, buyAllOut;
			BotSettings botSettings = new BotSettings();

			// Объявляем и забиваем файл в документ  
			XmlDocument xd = new XmlDocument();
			FileStream fs = new FileStream(filepath, FileMode.Open);
			xd.Load(fs);

			XmlNodeList list = xd.GetElementsByTagName("setting"); // Создаем и заполняем лист по тегу "settings"  
			for (int i = 0; i < list.Count; i++)
			{
				XmlElement id = (XmlElement)xd.GetElementsByTagName("setting")[i];
				XmlElement eworkLogin = (XmlElement)xd.GetElementsByTagName("worklogin")[i];	  // Забиваем login в переменную  
				XmlElement eworkPass = (XmlElement)xd.GetElementsByTagName("workpass")[i];	  // Забиваем login в переменную  
				XmlElement eworkServ = (XmlElement)xd.GetElementsByTagName("workserv")[i];	  // Забиваем login в переменную  
				XmlElement ehedjLogin = (XmlElement)xd.GetElementsByTagName("hedjlogin")[i];	  // Забиваем login в переменную  
				XmlElement ehedjPass = (XmlElement)xd.GetElementsByTagName("hedjpass")[i];	  // Забиваем login в переменную  
				XmlElement ehedjServ = (XmlElement)xd.GetElementsByTagName("hedjserv")[i];	  // Забиваем login в переменную  

				XmlElement eworkSec = (XmlElement)xd.GetElementsByTagName("worksec")[i];	  // Забиваем login в переменную  
				XmlElement eworkVol = (XmlElement)xd.GetElementsByTagName("workvol")[i];	  // Забиваем login в переменную  
                XmlElement eworkVol2 = (XmlElement)xd.GetElementsByTagName("workvol2")[i];	  // Забиваем login в переменную  
                XmlElement eworkVol3 = (XmlElement)xd.GetElementsByTagName("workvol3")[i];	  // Забиваем login в переменную  
                XmlElement eworkVol4 = (XmlElement)xd.GetElementsByTagName("workvol4")[i];	  // Забиваем login в переменную  
				XmlElement ehedjSec = (XmlElement)xd.GetElementsByTagName("hedjsec")[i];	  // Забиваем login в переменную  
				XmlElement ekHedj = (XmlElement)xd.GetElementsByTagName("khedj")[i];	  // Забиваем login в переменную  

				XmlElement esellDisp = (XmlElement)xd.GetElementsByTagName("selldisp")[i];	  // Забиваем login в переменную  
				XmlElement ebuyDisp = (XmlElement)xd.GetElementsByTagName("buydisp")[i];	  // Забиваем login в переменную  

				XmlElement epackage = (XmlElement)xd.GetElementsByTagName("package")[i];	  // Забиваем login в переменную  
				XmlElement eaveraging = (XmlElement)xd.GetElementsByTagName("averaging")[i];	  // Забиваем login в переменную  
				XmlElement emax = (XmlElement)xd.GetElementsByTagName("max")[i];	  // Забиваем login в переменную  
				XmlElement ehotelka = (XmlElement)xd.GetElementsByTagName("hotelka")[i];	  // Забиваем login в переменную  

                XmlElement epackage2 = (XmlElement)xd.GetElementsByTagName("package2")[i];	  // Забиваем login в переменную  
                XmlElement eaveraging2 = (XmlElement)xd.GetElementsByTagName("averaging2")[i];	  // Забиваем login в переменную  
                XmlElement emax2 = (XmlElement)xd.GetElementsByTagName("max2")[i];	  // Забиваем login в переменную  
                XmlElement ehotelka2 = (XmlElement)xd.GetElementsByTagName("hotelka2")[i];	  // Забиваем login в переменную  

                XmlElement eopora = (XmlElement)xd.GetElementsByTagName("opora")[i];	  // Забиваем login в переменную  
                XmlElement eopora2 = (XmlElement)xd.GetElementsByTagName("opora2")[i];	  // Забиваем login в переменную  
                XmlElement eopora3 = (XmlElement)xd.GetElementsByTagName("opora3")[i];	  // Забиваем login в переменную  
                XmlElement eopora4 = (XmlElement)xd.GetElementsByTagName("opora4")[i];	  // Забиваем login в переменную  

                XmlElement ebeforeHedj = (XmlElement)xd.GetElementsByTagName("beforeHedj")[i];	  // Забиваем login в переменную  
                XmlElement ebeforeWork = (XmlElement)xd.GetElementsByTagName("beforeWork")[i];	  // Забиваем login в переменную  
                XmlElement eKey = (XmlElement)xd.GetElementsByTagName("key")[i];	  // Забиваем login в переменную  

                XmlElement eTop = (XmlElement)xd.GetElementsByTagName("top")[i];	  // Забиваем login в переменную  
                XmlElement eLeft = (XmlElement)xd.GetElementsByTagName("left")[i];	  // Забиваем login в переменную  
                XmlElement estakanHole = (XmlElement)xd.GetElementsByTagName("stakanHole")[i];	  // Забиваем login в переменную  
                XmlElement ehedjMode = (XmlElement)xd.GetElementsByTagName("hedjMode")[i];	  // Забиваем login в переменную  
                XmlElement eautoStep = (XmlElement)xd.GetElementsByTagName("autoStep")[i];	  // Забиваем login в переменную  

                XmlElement esellAllIn = (XmlElement)xd.GetElementsByTagName("sellAllIn")[i];	  // Забиваем login в переменную  
                XmlElement esellAllOut = (XmlElement)xd.GetElementsByTagName("sellAllOut")[i];	  // Забиваем login в переменную  
                XmlElement ebuyAllIn = (XmlElement)xd.GetElementsByTagName("buyAllIn")[i];	  // Забиваем login в переменную  
                XmlElement ebuyAllOut = (XmlElement)xd.GetElementsByTagName("buyAllOut")[i];	  // Забиваем login в переменную  
				// Вставляем в переменные текст из тегов  
				if (id.GetAttribute("id") == "1")
				{
                    workLogin = (eworkLogin == null || string.IsNullOrEmpty(eworkLogin.InnerText)) ? "" : eworkLogin.InnerText;
                    workPass = (eworkPass == null || string.IsNullOrEmpty(eworkPass.InnerText)) ? "" : eworkPass.InnerText;
                    workServ = (eworkServ == null || string.IsNullOrEmpty(eworkServ.InnerText)) ? "" : eworkServ.InnerText;
                    hedjLogin = (ehedjLogin == null || string.IsNullOrEmpty(ehedjLogin.InnerText)) ? "" : ehedjLogin.InnerText;
                    hedjPass = (ehedjPass == null || string.IsNullOrEmpty(ehedjPass.InnerText)) ? "" : ehedjPass.InnerText;
                    hedjServ = (ehedjServ == null || string.IsNullOrEmpty(ehedjServ.InnerText)) ? "" : ehedjServ.InnerText;
                    workSec = (eworkSec == null || string.IsNullOrEmpty(eworkSec.InnerText)) ? "" : eworkSec.InnerText;

                    workVol = (eworkVol == null || string.IsNullOrEmpty(eworkVol.InnerText)) ? "0" : eworkVol.InnerText;
                    workVol2 = (eworkVol2 == null || string.IsNullOrEmpty(eworkVol2.InnerText)) ? "0" : eworkVol2.InnerText;
                    workVol3 = (eworkVol3 == null || string.IsNullOrEmpty(eworkVol3.InnerText)) ? "0" : eworkVol3.InnerText;
                    workVol4 = (eworkVol4 == null || string.IsNullOrEmpty(eworkVol4.InnerText)) ? "0" : eworkVol4.InnerText;

                    hedjSec = (ehedjSec == null || string.IsNullOrEmpty(ehedjSec.InnerText)) ? "" : ehedjSec.InnerText;
                    kHedj = (ekHedj == null || string.IsNullOrEmpty(ekHedj.InnerText)) ? "0" : ekHedj.InnerText;

                    sellDisp = (esellDisp == null || string.IsNullOrEmpty(esellDisp.InnerText)) ? "0" : esellDisp.InnerText;
                    buyDisp = (ebuyDisp == null || string.IsNullOrEmpty(ebuyDisp.InnerText)) ? "0" : ebuyDisp.InnerText;

                    package = (epackage == null || string.IsNullOrEmpty(epackage.InnerText)) ? "0" : epackage.InnerText;
                    averaging = (eaveraging == null || string.IsNullOrEmpty(eaveraging.InnerText)) ? "0" : eaveraging.InnerText;
                    max = (emax == null || string.IsNullOrEmpty(emax.InnerText)) ? "0" : emax.InnerText;
                    hotelka = (ehotelka == null || string.IsNullOrEmpty(ehotelka.InnerText)) ? "0" : ehotelka.InnerText;

                    package2 = (epackage2 == null || string.IsNullOrEmpty(epackage2.InnerText) || epackage2.InnerText == "0") ? package : epackage2.InnerText;
                    averaging2 = (eaveraging2 == null || string.IsNullOrEmpty(eaveraging2.InnerText)) ? averaging : eaveraging2.InnerText;
                    max2 = (emax2 == null || string.IsNullOrEmpty(emax2.InnerText)) ? max : emax2.InnerText;
                    hotelka2 = (ehotelka2 == null || string.IsNullOrEmpty(ehotelka2.InnerText)) ? hotelka : ehotelka2.InnerText;

                    opora = (eopora == null || string.IsNullOrEmpty(eopora.InnerText)) ? "0" : eopora.InnerText;
                    opora2 = (eopora2 == null || string.IsNullOrEmpty(eopora2.InnerText)) ? "0" : eopora2.InnerText;
                    opora3 = (eopora3 == null || string.IsNullOrEmpty(eopora3.InnerText)) ? "0" : eopora3.InnerText;
                    opora4 = (eopora4 == null || string.IsNullOrEmpty(eopora4.InnerText)) ? "0" : eopora4.InnerText;
                    beforeHedj = (ebeforeHedj == null || string.IsNullOrEmpty(ebeforeHedj.InnerText)) ? "0" : ebeforeHedj.InnerText;
                    beforeWork = (ebeforeWork == null || string.IsNullOrEmpty(ebeforeWork.InnerText)) ? "0" : ebeforeWork.InnerText;
                    key = (eKey == null || string.IsNullOrEmpty(eKey.InnerText)) ? "0" : eKey.InnerText;

                    top = (eTop == null || string.IsNullOrEmpty(eTop.InnerText)) ? "0" : eTop.InnerText;
                    left = (eLeft == null || string.IsNullOrEmpty(eLeft.InnerText)) ? "0" : eLeft.InnerText;
                    stakanHole = (estakanHole == null || string.IsNullOrEmpty(estakanHole.InnerText)) ? "0" : estakanHole.InnerText;
                    hedjMode = (ehedjMode == null || string.IsNullOrEmpty(ehedjMode.InnerText)) ? "0" : ehedjMode.InnerText;
                    autoStep = (eautoStep == null || string.IsNullOrEmpty(eautoStep.InnerText)) ? "1" : eautoStep.InnerText;

                    sellAllIn = (esellAllIn == null || string.IsNullOrEmpty(esellAllIn.InnerText)) ? "50000" : esellAllIn.InnerText;
                    sellAllOut = (esellAllOut == null || string.IsNullOrEmpty(esellAllOut.InnerText)) ? "-50000" : esellAllOut.InnerText;
                    buyAllIn = (ebuyAllIn == null || string.IsNullOrEmpty(ebuyAllIn.InnerText)) ? "-50000" : ebuyAllIn.InnerText;
                    buyAllOut = (ebuyAllOut == null || string.IsNullOrEmpty(ebuyAllOut.InnerText)) ? "50000" : ebuyAllOut.InnerText;

					// Заполняем поля настроек
					botSettings.WorkLogin = workLogin;
					botSettings.WorkPass = workPass;
					botSettings.WorkServ = workServ;
					botSettings.HedjLogin = hedjLogin;
					botSettings.HedjPass = hedjPass;
					botSettings.HedjServ = hedjServ;

					botSettings.WorkSec = workSec;
					botSettings.WorkVol = workVol;
                    botSettings.WorkVol2 = workVol2;
                    botSettings.WorkVol3 = workVol3;
                    botSettings.WorkVol4 = workVol4;
					botSettings.HedjSec = hedjSec;
					botSettings.KHedj = kHedj;

					botSettings.SellDisp = sellDisp;
					botSettings.BuyDisp = buyDisp;

					botSettings.Package = package;
					botSettings.Averaging = averaging;
					botSettings.Max = max;
					botSettings.Hotelka = hotelka;

                    botSettings.Package2 = package2;
                    botSettings.Averaging2 = averaging2;
                    botSettings.Max2 = max2;
                    botSettings.Hotelka2 = hotelka2;

                    botSettings.Opora = opora;
                    botSettings.Opora2 = opora2;
                    botSettings.Opora3 = opora3;
                    botSettings.Opora4 = opora4;

                    botSettings.BeforeHedj = beforeHedj;
                    botSettings.BeforeWork = beforeWork;
                    botSettings.Key = key;

                    botSettings.Top = top;
                    botSettings.Left = left;
                    botSettings.StakanHole = stakanHole;
                    botSettings.HedjMode = int.Parse(hedjMode);
                    botSettings.AutoStep = autoStep;
                    
                    botSettings.SellAllIn = sellAllIn;
                    botSettings.SellAllOut = sellAllOut;
                    botSettings.BuyAllIn = buyAllIn;
                    botSettings.BuyAllOut = buyAllOut;
				}
			}
			// Закрываем поток  
			fs.Close();
			return botSettings;
		} 

		private void CreateXMLDocument(string filepath)
		{
			XmlTextWriter xtw = new XmlTextWriter(filepath, Encoding.UTF8);
			xtw.WriteStartDocument();
			xtw.WriteStartElement("settings");
			xtw.WriteEndDocument();
			xtw.Close();
		}

		#endregion Загрузка и сохранение свойств

		#region Показ и скрытие панелей

		public bool IsSlotsPanelVisible { get { return slotsPanel.Visible; } set { slotsPanel.Visible = value; if (value) slotsButton.BackColor = Color.Yellow; else slotsButton.BackColor = m_DefCol; SetPanelsPositions(); } }
		public bool IsSecsPanelVisible { get { return secsPanel.Visible; } set { secsPanel.Visible = value; if (value) secsButton.BackColor = Color.Yellow; else secsButton.BackColor = m_DefCol; SetPanelsPositions(); } }
		public bool IsDispsPanelVisible { get { return dispsPanel.Visible; } set { dispsPanel.Visible = value; if (value) dispsButton.BackColor = Color.Yellow; else dispsButton.BackColor = m_DefCol; SetPanelsPositions(); } }
		public bool IsAveragingPanelVisible { get { return averagingPanel.Visible; } set { averagingPanel.Visible = value; if (value) averagingButton.BackColor = Color.Yellow; else averagingButton.BackColor = m_DefCol; SetPanelsPositions(); } }
        public bool IsKeyPanelVisible { get { return keyPanel.Visible; } set { keyPanel.Visible = value; if (value) enterKeyButton.BackColor = Color.Yellow; else enterKeyButton.BackColor = m_DefCol; SetPanelsPositions(); } }

		public enum PanelsPriority
		{
			ppSlotsPanel = 50,
			ppSecsPanel = 100,
			ppDispsPanel = 150,
			ppAvaredgingPanel = 200,
            ppKeyPanel = 250,
		}

		private Color m_DefCol;

		private void SetPanelsPositions()
		{
			slotsPanel.Top = (int)PanelsPriority.ppSlotsPanel;
			//------------
			if (IsSlotsPanelVisible)
				secsPanel.Top = (int)PanelsPriority.ppSecsPanel;
			else
				secsPanel.Top = (int)PanelsPriority.ppSlotsPanel;
			//------------
			if (IsSlotsPanelVisible && IsSecsPanelVisible)
				dispsPanel.Top = (int)PanelsPriority.ppDispsPanel;
			else
				if (IsSlotsPanelVisible || IsSecsPanelVisible)
					dispsPanel.Top = (int)PanelsPriority.ppSecsPanel;
				else
					dispsPanel.Top = (int)PanelsPriority.ppSlotsPanel;
			//------------
			if (IsSlotsPanelVisible && IsSecsPanelVisible && IsDispsPanelVisible)
				averagingPanel.Top = (int)PanelsPriority.ppAvaredgingPanel;
			else
				if ((IsSlotsPanelVisible && IsSecsPanelVisible) || (IsSlotsPanelVisible && IsDispsPanelVisible) || (IsSecsPanelVisible && IsDispsPanelVisible))
				{
					if (IsDispsPanelVisible)
						averagingPanel.Top = (int)PanelsPriority.ppDispsPanel;
					else
						averagingPanel.Top = (int)PanelsPriority.ppDispsPanel;
				}
				else
					if (IsSlotsPanelVisible || IsSecsPanelVisible || IsDispsPanelVisible)
						averagingPanel.Top = (int)PanelsPriority.ppSecsPanel;
					else
						averagingPanel.Top = (int)PanelsPriority.ppSlotsPanel;

            //------------
            if (IsSlotsPanelVisible && IsSecsPanelVisible && IsDispsPanelVisible && IsAveragingPanelVisible)
                keyPanel.Top = (int)PanelsPriority.ppKeyPanel; else
                if (IsSlotsPanelVisible && IsSecsPanelVisible && IsDispsPanelVisible && !IsAveragingPanelVisible)
                    keyPanel.Top = (int)PanelsPriority.ppDispsPanel; else
                    if (IsSlotsPanelVisible && IsSecsPanelVisible && !IsDispsPanelVisible && IsAveragingPanelVisible)
                        keyPanel.Top = (int)PanelsPriority.ppKeyPanel; else
                        if (IsSlotsPanelVisible && IsSecsPanelVisible && !IsDispsPanelVisible && !IsAveragingPanelVisible)
                            keyPanel.Top = (int)PanelsPriority.ppSecsPanel; else
                            if (IsSlotsPanelVisible && !IsSecsPanelVisible && IsDispsPanelVisible && IsAveragingPanelVisible)
                                keyPanel.Top = (int)PanelsPriority.ppAvaredgingPanel; else
                                if (IsSlotsPanelVisible && !IsSecsPanelVisible && IsDispsPanelVisible && !IsAveragingPanelVisible)
                                    keyPanel.Top = (int)PanelsPriority.ppDispsPanel; else
                                    if (IsSlotsPanelVisible && !IsSecsPanelVisible && !IsDispsPanelVisible && !IsAveragingPanelVisible)
                                        keyPanel.Top = (int)PanelsPriority.ppSecsPanel; else
                                        if (!IsSlotsPanelVisible && IsSecsPanelVisible && IsDispsPanelVisible && IsAveragingPanelVisible)
                                            keyPanel.Top = (int)PanelsPriority.ppAvaredgingPanel; else
                                            if (!IsSlotsPanelVisible && IsSecsPanelVisible && IsDispsPanelVisible && !IsAveragingPanelVisible)
                                                keyPanel.Top = (int)PanelsPriority.ppDispsPanel; else
                                                if (!IsSlotsPanelVisible && IsSecsPanelVisible && !IsDispsPanelVisible && IsAveragingPanelVisible)
                                                    keyPanel.Top = (int)PanelsPriority.ppDispsPanel; else
                                                    if (!IsSlotsPanelVisible && IsSecsPanelVisible && !IsDispsPanelVisible && !IsAveragingPanelVisible)
                                                        keyPanel.Top = (int)PanelsPriority.ppSecsPanel; else
                                                        if (!IsSlotsPanelVisible && !IsSecsPanelVisible && IsDispsPanelVisible && IsAveragingPanelVisible)
                                                            keyPanel.Top = (int)PanelsPriority.ppDispsPanel; else
                                                            if (!IsSlotsPanelVisible && !IsSecsPanelVisible && IsDispsPanelVisible && !IsAveragingPanelVisible)
                                                                keyPanel.Top = (int)PanelsPriority.ppSecsPanel; else
                                                                if (!IsSlotsPanelVisible && !IsSecsPanelVisible && !IsDispsPanelVisible && !IsAveragingPanelVisible)
                                                                    keyPanel.Top = (int)PanelsPriority.ppSlotsPanel;
                                                                    

		}

		private void slotsButton_Click(object sender, EventArgs e)
		{
			if (this.IsSlotsPanelVisible) 
				this.IsSlotsPanelVisible = false;
			else
				this.IsSlotsPanelVisible = true;
		}

		private void secsButton_Click(object sender, EventArgs e)
		{
			if (this.IsSecsPanelVisible)
				this.IsSecsPanelVisible = false;
			else
				this.IsSecsPanelVisible = true;
		}

		private void dispsButton_Click(object sender, EventArgs e)
		{
			if (this.IsDispsPanelVisible)
				this.IsDispsPanelVisible = false;
			else
				this.IsDispsPanelVisible = true;
		}

		private void averagingButton_Click(object sender, EventArgs e)
		{
			if (this.IsAveragingPanelVisible)
				this.IsAveragingPanelVisible = false;
			else
				this.IsAveragingPanelVisible = true;
		}

        private void enterKeyButton_Click(object sender, EventArgs e)
        {
            if (this.IsKeyPanelVisible)
                this.IsKeyPanelVisible = false;
            else
                this.IsKeyPanelVisible = true;
        }

		RoboMode curMode = RoboMode.rmMonitor;
		private void tradingModeComboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			switch (tradingModeComboBox.SelectedIndex)
			{
				case 0: curMode = RoboMode.rmMonitor; break;
				case 1: curMode = RoboMode.rmLimitFromSell; break;
				case 2: curMode = RoboMode.rmLimitTwoWay; break;
                case 3: curMode = RoboMode.rmLimitFromBuy; break;

				default:
					break;
			}
			if (this.tradingModeComboBox.SelectedIndex > 0)
			{
				this.IsSlotsPanelVisible = this.IsSecsPanelVisible = this.IsDispsPanelVisible = this.IsAveragingPanelVisible = this.IsKeyPanelVisible = false;
				this.mainPanel.Height = 24;
			}
			else
				this.mainPanel.Height = 48;
		}
		#endregion Показ и скрытие панелей

		#region Подключение рабочего

		private AtentisWrapper aWorkWrap;
		private AtentisConnection aWorkCon;
		private bool m_WorkConnected = false;
		private bool m_WorkFILoaded;

		private void connectWorkButton_Click(object sender, EventArgs e)
		{
			ConnectWork();
		}

        private bool m_WorkSyncronized = false;

		private void ConnectWork()
		{
			if (!this.m_WorkConnected)
			{
				AcceptSettings();

				aWorkWrap = new AtentisWrapper();
				aWorkCon = (AtentisConnection)aWorkWrap.AddConnection("DataSlot", m_BotSettings.WorkServ, m_BotSettings.WorkLogin, m_BotSettings.WorkPass);
				/*
				aWorkCon.Connected += aWorkCon_Connected;
				aWorkCon.SecMaster.HasNewTrade += SecMaster_HasNewTrade;
				*/
				aWorkCon.SecMaster.FILoaded += SecMaster_WorkFILoaded;
				aWorkCon.SecMaster.SellOrderComplete += SecMaster_WorkSellOrderComplete;
				aWorkCon.SecMaster.BuyOrderComplete += SecMaster_WorkBuyOrderComplete;
				aWorkCon.SecMaster.PositionsUpdated += SecMaster_WorkPositionsUpdated;
				aWorkCon.SecMaster.HoldingsUpdated += SecMaster_WorkHoldingsUpdated;
				aWorkCon.SecMaster.OrderbookUpdated += SecMaster_WorkOrderbookUpdated;
                aWorkCon.SecMaster.OrderbookReplBegin += SecMaster_WorkOrderbookReplBegin;
                aWorkCon.SecMaster.OrderbookReplEnd += SecMaster_WorkOrderbookReplEnd;

				//OpenTables(aWorkCon);
                OpenSecurities(aWorkCon);

				aWorkCon.Connect();
				aWorkCon.RefreshFreq = 1;
                //aWorkCon.Connected += new EventHandler(aWorkWrap_Synchronized);
                aWorkWrap.Synchronized +=new EventHandler(aWorkWrap_Synchronized);
                while (!m_WorkSyncronized) Thread.Sleep(10);
                
                string path = Application.ExecutablePath;
                DateTime fileCreatedDate = File.GetLastWriteTime(path);
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("-=file_created=- :" + fileCreatedDate)));
                
				m_WorkConnected = true;
				this.connectWorkButton.Text = "Отключить";

			}
			else
			{
				aWorkCon.Disconnect();
				m_WorkConnected = false;
				this.workSecsСomboBox.Items.Clear();
				this.workSecsСomboBox.Text = string.Empty;
				this.connectWorkButton.Text = "Подключить";
			}
		}

        void aWorkWrap_Synchronized(object sender, EventArgs e)
        {
            m_WorkSyncronized = true;
        }

		void SecMaster_WorkFILoaded(object sender, EventArgs e)
		{
            aWorkCon.CloseTable(WrapperEnums.AllTables.atSECURITIES);
			m_WorkFILoaded = true;
		}

		private void workSecTimer_Tick(object sender, EventArgs e)
		{
			if (m_WorkFILoaded && aWorkCon != null && aWorkCon.WSerurities != null && aWorkCon.WSerurities.Count() > 1)
			{
				//var count = aCon.WFirm_Holding_Total.Count();
				var count = aWorkCon.WSerurities.Count();
				for (int i = 0; i < count; i++)
				{
					//var elem = aCon.WFirm_Holding_Total[i];
					var elem = aWorkCon.WSerurities[i];
					if (elem != null) this.workSecsСomboBox.Items.Add(elem.ShortName);
				}
				//this.workSecsСomboBox.SelectedIndex = 1;
				int pos = this.workSecsСomboBox.Items.IndexOf(this.workSecsСomboBox.Text);
                if (this.workSecsСomboBox.Text != "Выбрать..." && this.workSecsСomboBox.Text != "")
                {
                    this.workSecsСomboBox.SelectedIndex = pos;
                    m_WorkSecsСomboBoxText = workSecsСomboBox.Text;
                }
                else
                    this.workSecsСomboBox.Text = "Выбрать...";

				this.workSecTimer.Stop();
				this.workSecTimer.Enabled = false;
                OpenTables(aWorkCon);
			}
		}
        private bool IsLastPartOfSell = false;
		void SecMaster_WorkSellOrderComplete(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var row = e as AtentisConnectorEventArgs;
                if (row != null && row.WrapperTradesRow.SecCode == m_BotSettings.WorkSecurity.SecCode)
				{
                    while (m_LastWorkSellOrder.OrderNo == 0)
                    {
                        Thread.Sleep(2);
                        Application.DoEvents();
                    }
					var trdRow = row.WrapperTradesRow;
                    m_LastWorkSellOrder.Amount -= trdRow.Quantity;
                    if (m_LastWorkSellOrder.Amount == 0)
                        IsLastPartOfSell = true;

                    if (trdRow.OrderNo != m_LastWorkSellOrder.OrderNo)
                    {
                        if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ФОРТС: Не совпадение номера заявки {0} с номером последнего ордера на продажу! {1}", trdRow.OrderNo, m_LastWorkSellOrder.OrderNo)));
                    }
                    m_LastDelWorkResult = 0;
                    if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ФОРТС: : Исполнена часть продажи форта, равная {0}; осталось {1}", trdRow.Quantity, m_LastWorkSellOrder.Amount)));
                    HedjLastSell(trdRow.Quantity);
				}
			}
		}
        private bool IsLastPartOfBuy = false;
		void SecMaster_WorkBuyOrderComplete(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var row = e as AtentisConnectorEventArgs;
                if (row != null && row.WrapperTradesRow.SecCode == m_BotSettings.WorkSecurity.SecCode)
				{
					var trdRow = row.WrapperTradesRow;
                    while (m_LastWorkBuyOrder.OrderNo == 0)
                    {
                        Thread.Sleep(2);
                        Application.DoEvents();
                    }

                    m_LastWorkBuyOrder.Amount -= trdRow.Quantity;
                    if (m_LastWorkBuyOrder.Amount == 0)
                        IsLastPartOfBuy = true;

                    if (trdRow.OrderNo != m_LastWorkBuyOrder.OrderNo)
                    {
                        if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ФОРТС: Не совпадение номера заявки {0} с номером последнего ордера на покупку! {1}", trdRow.OrderNo, m_LastWorkBuyOrder.OrderNo)));
                    }
                    m_LastDelWorkResult = 0;
                    if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ФОРТС: : Исполнена часть покупки форта, равная {0}; осталось {1}", trdRow.Quantity, m_LastWorkBuyOrder.Amount)));
                    HedjLastBuy(trdRow.Quantity);
				}
			}
		}

        private double m_WorkCurPos = 0;
		void SecMaster_WorkPositionsUpdated(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
                var row = (e as AtentisConnectorEventArgs).WrapperPositions;
                m_WorkCurPos = row.CBPLimit - row.CBPLUsed;
			}
		}

		private int m_ConCount = 0;
		void SecMaster_WorkHoldingsUpdated(object sender, EventArgs e)
		{
            /*
			if (e is AtentisConnectorEventArgs)
			{
                if ((e as AtentisConnectorEventArgs).WrapperHoldings.SecCode == m_BotSettings.WorkSecurity.SecCode)
                    PerformDisp();
			}
            */
		}

        private void GetConCount()
        {
            if (aWorkCon == null) return;
            if (aWorkCon.WFirm_Holding_Total != null && aWorkCon.WFirm_Holding_Total.Count > 0)
            {
                if (m_BotSettings.WorkSecurity != null)
                {
                    var p = aWorkCon.WFirm_Holding_Total.Find(x => x.SecCode == m_BotSettings.WorkSecurity.SecCode);
                    if (p != null)
                        m_ConCount = (int)p.CurrentPos;
                }
            }

            if (aHedjCon == null) return;
            if (aHedjCon.WFirm_Holding_Total != null && aHedjCon.WFirm_Holding_Total.Count > 0)
            {
                if (m_BotSettings.HedjSecurity != null)
                {
                    var p = aHedjCon.WFirm_Holding_Total.Find(x => x.SecCode == m_BotSettings.HedjSecurity.SecCode);
                    if (p != null)
                    {
                        m_HedjConCount = (int)p.CurrentPos;
                        m_MinPos = p.Min;
                    }
                }
            }
            if (m_ConCount == 0 || m_HedjConCount == 0 || m_MinPos == 0)
                Console.Write("");
        }


        private static void OpenSecurities(AtentisConnection con)
        {

            con.OpenTable(WrapperEnums.AllTables.atSECURITIES, "", "");
            //con.OpenTable(WrapperEnums.AllTables.atINDEXES, "", "");
            //con.OpenTable(WrapperEnums.AllTables.atBOARDS, "", "");
            //con.OpenTable(WrapperEnums.AllTables.atHISTORY, "", "");
            //con.OpenTable(WrapperEnums.AllTables.atHISTORY_DAILY, "", "");
            //con.OpenTable(WrapperEnums.AllTables.atNEWS, "", "");
            con.OpenTable(WrapperEnums.AllTables.atFIRM_HOLDING_TOTAL, "", "");
            con.OpenTable(WrapperEnums.AllTables.atORDERS, "", "");
            con.OpenTable(WrapperEnums.AllTables.atPOSITIONS, "", "");
            //con.OpenTable(WrapperEnums.AllTables.atSTOPORDERS, "", "");
            //con.OpenTable(WrapperEnums.AllTables.atTESYSTIME, "", "");
            con.OpenTable(WrapperEnums.AllTables.atTRADES, "", "");
            con.OpenTable(WrapperEnums.AllTables.atTRDACC, "", "");
            //con.OpenTable(WrapperEnums.AllTables.atALL_TRADES, "", "");
        }

		private static void OpenTables(AtentisConnection con)
		{
			//********
		}

		#endregion Подключение рабочего

		#region Подключение хеджера

		private AtentisWrapper aHedjWrap;
		private AtentisConnection aHedjCon;
		private bool m_HedjConnected = false;
		private bool m_HedjFILoaded;

		private void connectHedjButton_Click(object sender, EventArgs e)
		{
			ConnectHedj();
		}

        private bool m_HedjSyncronized = false;

		private void ConnectHedj()
		{
			if (!this.m_HedjConnected)
			{
				AcceptSettings();

				aHedjWrap = new AtentisWrapper();
				aHedjCon = (AtentisConnection)aHedjWrap.AddConnection("DataSlot", m_BotSettings.HedjServ, m_BotSettings.HedjLogin, m_BotSettings.HedjPass);
				/*
				aHedjCon.Connected += aHedjCon_Connected;
				aHedjCon.SecMaster.HasNewTrade += SecMaster_HasNewTrade;
				*/
				aHedjCon.SecMaster.FILoaded += SecMaster_HedjFILoaded;
				aHedjCon.SecMaster.SellOrderComplete += SecMaster_HedjSellOrderComplete;
				aHedjCon.SecMaster.BuyOrderComplete += SecMaster_HedjBuyOrderComplete;
				aHedjCon.SecMaster.PositionsUpdated += SecMaster_HedjPositionsUpdated;
				aHedjCon.SecMaster.OrderbookUpdated += SecMaster_HedjOrderbookUpdated;
                aHedjCon.SecMaster.OrderbookReplBegin += SecMaster_HedjOrderbookReplBegin;
                aHedjCon.SecMaster.OrderbookReplEnd += SecMaster_HedjOrderbookReplEnd;
                aHedjCon.SecMaster.HoldingsUpdated += SecMaster_HedjHoldingsUpdated;

				//OpenTables(aHedjCon);
                OpenSecurities(aHedjCon);

				aHedjCon.Connect();
				aHedjCon.RefreshFreq = 1;

                //aHedjCon.Connected += new EventHandler(aHedjWrap_Synchronized);
                aHedjWrap.Synchronized += new EventHandler(aHedjWrap_Synchronized);
                while (!m_HedjSyncronized) Thread.Sleep(10);

				m_HedjConnected = true;
				this.connectHedjButton.Text = "Отключить";

			}
			else
			{
				aHedjCon.Disconnect();
				m_HedjConnected = false;
				this.hedjSecsСomboBox.Items.Clear();
				this.hedjSecsСomboBox.Text = string.Empty;
				this.connectHedjButton.Text = "Подключить";
			}
		}

        private int m_HedjConCount = 0;
        private long m_MinPos = 0;
        void SecMaster_HedjHoldingsUpdated(object sender, EventArgs e)
        {
            /*
            if (e is AtentisConnectorEventArgs)
            {
                var p = e  as AtentisConnectorEventArgs;
                if (p.WrapperHoldings.SecCode == m_BotSettings.HedjSecurity.SecCode)
                {
                    m_MinPos = p.WrapperHoldings.Min;
                    PerformDisp();
                }
            }
            */
        }

        void aHedjWrap_Synchronized(object sender, EventArgs e)
        {
            m_HedjSyncronized = true;
        }

		void SecMaster_HedjFILoaded(object sender, EventArgs e)
		{
            aHedjCon.CloseTable(WrapperEnums.AllTables.atSECURITIES);
			m_HedjFILoaded = true;
		}

		private void hedjSecTimer_Tick(object sender, EventArgs e)
		{
			if (m_HedjFILoaded && aHedjCon != null && aHedjCon.WSerurities != null && aHedjCon.WSerurities.Count() > 1)
			{
				//var count = aCon.WFirm_Holding_Total.Count();
				var count = aHedjCon.WSerurities.Count();
				for (int i = 0; i < count; i++)
				{
					//var elem = aCon.WFirm_Holding_Total[i];
					var elem = aHedjCon.WSerurities[i];
					if (elem != null) this.hedjSecsСomboBox.Items.Add(elem.ShortName);
				}
				//this.hedjSecsСomboBox.SelectedIndex = 1;
				int pos = this.hedjSecsСomboBox.Items.IndexOf(this.hedjSecsСomboBox.Text);
                if (this.hedjSecsСomboBox.Text != "Выбрать..." && this.hedjSecsСomboBox.Text != "")
                {
                    this.hedjSecsСomboBox.SelectedIndex = pos;
                    m_HedjSecsСomboBoxText = hedjSecsСomboBox.Text;
                }
                else
                    this.hedjSecsСomboBox.Text = "Выбрать...";

				this.hedjSecTimer.Stop();
				this.hedjSecTimer.Enabled = false;
                OpenTables(aHedjCon);
			}
		}

		void SecMaster_HedjSellOrderComplete(object sender, EventArgs e)
		{
            if (e is AtentisConnectorEventArgs)
            {
                var row = e as AtentisConnectorEventArgs;
                if (row != null && row.WrapperTradesRow.SecCode == m_BotSettings.HedjSecurity.SecCode)
                {
                    var trdRow = row.WrapperTradesRow;
                    if (trdRow.OrderNo != m_LastHedjSellOrder.OrderNo)
                        if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ММВБ: Не совпадение номера заявки {0} с номером последнего ордера на продажу! {1}", trdRow.OrderNo, m_LastHedjSellOrder.OrderNo)));

                    m_LastHedjSellOrder.Amount -= trdRow.Quantity;
                    if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ММВБ: Исполнена часть продажи спота, равная {0}", trdRow.Quantity)));
                    if (IsLastPartOfBuy && m_BuyHedjNeedVol == 0 && m_LastHedjSellOrder.Amount == 0)
                    {
                        if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ММВБ: Скинем покупку, т.к.: m_LastHedjSellOrder.Amount = {0} && IsLastPartOfBuy = {1} && m_BuyHedjNeedVol = {2}", m_LastHedjSellOrder.Amount, IsLastPartOfBuy, m_BuyHedjNeedVol)));
                        ResetBuy();
                    }
                    else
                    {
                        if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ММВБ: НЕ Скинем покупку! т.к.: m_LastHedjSellOrder.Amount = {0} && IsLastPartOfBuy = {1} && m_BuyHedjNeedVol = {2}", m_LastHedjSellOrder.Amount, IsLastPartOfBuy, m_BuyHedjNeedVol)));
                        if (m_LastHedjSellOrder.Amount == 0)
                        {
                            if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ММВБ: Учтем исполненую часть продажи спота, равную {0}", trdRow.Quantity)));
                            m_IsBuyHedjMadeFull = true;
                        }
                        else
                            if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ММВБ:  НЕ Учтем исполненую часть продажи спота, равную {0}, т.к. m_LastHedjSellOrder.Amount = {1} && IsLastPartOfBuy = {2}", trdRow.Quantity, m_LastHedjSellOrder.Amount, IsLastPartOfBuy)));
                    }

                }
            }
		}

		void SecMaster_HedjBuyOrderComplete(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var row = e as AtentisConnectorEventArgs;
				if (row != null && row.WrapperTradesRow.SecCode == m_BotSettings.HedjSecurity.SecCode)
				{
					var trdRow = row.WrapperTradesRow;
					if (trdRow.OrderNo != m_LastHedjBuyOrder.OrderNo)
                        if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ММВБ: Не совпадение номера заявки {0} с номером последнего ордера на покупку! {1}", trdRow.OrderNo, m_LastHedjBuyOrder.OrderNo)));

					m_LastHedjBuyOrder.Amount -= trdRow.Quantity;
                    if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ММВБ: Исполнена часть покупки спота, равная {0}", trdRow.Quantity)));
                    if (IsLastPartOfSell && m_SellHedjNeedVol == 0 && m_LastHedjBuyOrder.Amount == 0)
                    {
                        if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ММВБ: Скинем продажу, т.к.: m_LastHedjBuyOrder.Amount = {0} && IsLastPartOfSell = {1} && m_BuyHedjNeedVol = {2}", m_LastHedjBuyOrder.Amount, IsLastPartOfSell, m_SellHedjNeedVol)));
                        ResetSell();
                    }
                    else
                    {
                        if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ММВБ: НЕ Скинем продажу! т.к.: m_LastHedjBuyOrder.Amount = {0} && IsLastPartOfSell = {1} && m_BuyHedjNeedVol = {2}", m_LastHedjBuyOrder.Amount, IsLastPartOfSell, m_SellHedjNeedVol)));
                        if (m_LastHedjBuyOrder.Amount == 0)
                        {
                            if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ММВБ: Учтем исполненую часть покупки спота, равнуя {0}", trdRow.Quantity)));
                            m_IsSellHedjMadeFull = true;
                        }
                        else
                            if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ММВБ:  НЕ Учтем исполненую часть покупки спота, равную {0}, т.к. m_LastHedjBuyOrder.Amount = {1} && IsLastPartOfSell = {2}", trdRow.Quantity, m_LastHedjBuyOrder.Amount, IsLastPartOfSell)));
                    }
				}
			}
		}

        private void ResetSell()
        {
            m_MayInSell = false;
            IsLastPartOfSell = false;
            //m_LastHedjBuyOrder.Price = -1;
            //m_LastWorkSellOrder.Price = -1;
            m_LastDelWorkResult = 0;
            m_LastDelHedjResult = 0;
            m_IsSellHedjMadeFull = true;
            m_SellHedjTime = false;
            if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ФОРТС:{0}, СПОТ:{1}", m_ConCount, m_HedjConCount)));
        }

        private void ResetBuy()
        {
            m_MayInBuy = false;
            IsLastPartOfBuy = false;
            //m_LastHedjSellOrder.Price = -1;
            //m_LastWorkBuyOrder.Price = -1;
            m_LastDelWorkResult = 0;
            m_LastDelHedjResult = 0;
            m_IsBuyHedjMadeFull = true;
            m_BuyHedjTime = false;
            if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("ФОРТС:{0}, СПОТ:{1}", m_ConCount, m_HedjConCount)));
        }

        private double m_HedjCurPos = 0;
		void SecMaster_HedjPositionsUpdated(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
                var row = (e as AtentisConnectorEventArgs).WrapperPositions;
                m_HedjCurPos = row.CurrentPos;
			}
		}

		#endregion Подключение хеджера

		#region Выбор рабочего

		private void workSecsСomboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
            //m_WorkSecsСomboBoxText = workSecsСomboBox.Text;
		}

		#endregion Выбор рабочего

		#region Выбор хеджера

		private void hedjSecsСomboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
            //m_HedjSecsСomboBoxText = hedjSecsСomboBox.Text;
		}

		#endregion Выбор хеджера

		#region Обработка стакана рабочего

		WrapperOrderbook m_WorkLastRow = new WrapperOrderbook();
		double m_WorkBestBuy = 0;
		double m_WorkBestSell = 0;

        
        void SecMaster_WorkOrderbookReplBegin(object sender, EventArgs e)
        {

        }
        void SecMaster_WorkOrderbookReplEnd(object sender, EventArgs e)
        {
            if (e is AtentisConnectorEventArgs)
            {
                var dr = e as AtentisConnectorEventArgs;
                var orderbook = dr.WrapperOrderbook;
                ProcessWorkStakan(orderbook);
                if (!m_PassCheked)
                    CheckPass();
            }
        }

        private bool m_PassCheked = false;
        private void CheckPass()
        {
            m_PassCheked = true;
            if (!CheckKey())
            {
                //this.SetPropertyThreadSafe(() => enterKeyButton.ForeColor, Color.White);
                Application.Exit();
            }
        }

        void SecMaster_WorkOrderbookUpdated(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var dr = e as AtentisConnectorEventArgs;
				var row = dr.WrapperOrderbookRow;
			}
		}

        private int m_BeforeWorkSellVol = 0;
        private int m_BeforeWorkBuyVol = 0;

        private List<WrapperOrderbook> m_WorkOrderbook = new List<WrapperOrderbook>();
        private void ProcessWorkStakan(List<WrapperOrderbook> orderbook)
        {
            lock (m_WorkOrderbook)
            {
                m_BeforeWorkSellVol = -1;
                m_BeforeWorkBuyVol = -1;

                m_WorkBestBuy = -1;
                m_WorkBestSell = -1;

                var sortedOrderbook = orderbook.OrderBy(x => x.Price);
                m_WorkOrderbook.Clear();
                foreach (var row in sortedOrderbook)
                    m_WorkOrderbook.Add(row);

                int buyIndex = -1;
                int sellIndex = -1;
                if (m_WorkOrderbook.Count > 10)
                {
                    for (int i = 0; i < m_WorkOrderbook.Count - 1; i++)
                    {
                        if (m_WorkOrderbook[i].BuySell == "B" && m_WorkOrderbook[i + 1].BuySell == "S")
                        {
                            buyIndex = i;
                            sellIndex = i + 1;
                        }
                    }

                    if (buyIndex < 0 || sellIndex < 0)
                    {
                        if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("m_WorkOrderbook.Count = {0}", m_WorkOrderbook.Count)));
                        return;
                    }

                    m_WorkBestBuy = m_WorkOrderbook[buyIndex].Price;
                    m_WorkBestSell = m_WorkOrderbook[sellIndex].Price;

                    int buyVol = 0;
                    //ищем лучшую цену покупки спота с учетом опорника
                    for (int i = buyIndex; i >= 0; i--)
                    {
                        var row = m_WorkOrderbook[i];
                        buyVol += row.Quantity;
                        if (m_WorkBestBuy < 0 && buyVol >= m_BotSettings.IntCurOpora)
                            m_WorkBestBuy = row.Price;
                        if (m_LastWorkBuyOrder.Price > 0)
                        {
                            if (m_LastWorkBuyOrder.Price <= row.Price)
                                m_BeforeWorkBuyVol = buyVol;
                        }
                        else
                            if (m_WorkBestBuy > 0) break;

                    }

                    int sellVol = 0;
                    //ищем лучшую цену продажи спота с учетом опорника
                    for (int i = sellIndex; i < m_WorkOrderbook.Count - 1; i++)
                    {
                        var row = m_WorkOrderbook[i];
                        sellVol += row.Quantity;
                        if (m_WorkBestSell < 0 && sellVol >= m_BotSettings.IntCurOpora)
                            m_WorkBestSell = row.Price;
                        if (m_LastWorkSellOrder.Price > 0)
                        {
                            if (m_LastWorkSellOrder.Price >= row.Price)
                                m_BeforeWorkSellVol = sellVol;
                        }
                        else
                            if (m_WorkBestSell > 0) break;
                    }
                }
                else
                    if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("m_SellDisp = {0}, m_BuyDisp = {1}, hedjBestBuy = {2}, hedjBestSell = {3}, workBestBuy = {4}, workBestSell = {5}", m_SellDisp, m_BuyDisp, m_HedjBestBuy, m_HedjBestSell, m_WorkBestBuy, m_WorkBestSell)));

                if (m_WorkPingReply != null && m_HedjPingReply != null)
                    if (m_WorkPingReply.RoundtripTime < MAXPING && m_HedjPingReply.RoundtripTime < MAXPING)
                        TryProcessDisp();
            }
        }

		#endregion Обработка стакана рабочего

		#region Обработка стакана хеджера
        void SecMaster_HedjOrderbookReplBegin(object sender, EventArgs e)
        {
        }
        void SecMaster_HedjOrderbookReplEnd(object sender, EventArgs e)
        {
            if (e is AtentisConnectorEventArgs)
            {
                var dr = e as AtentisConnectorEventArgs;
                var orderbook = dr.WrapperOrderbook;
                ProcessHedjStakan(orderbook);
            }
        }

		WrapperOrderbook m_HedjLastRow = new WrapperOrderbook();
		double m_HedjBestBuy = 0;
		double m_HedjBestSell = 0;
        double m_HedjBestBuyBehindVolume = 0;
        double m_HedjBestSellBehindVolume = 0;

        private int m_BeforeSellVol = 0;
        private int m_BeforeBuyVol = 0;

		void SecMaster_HedjOrderbookUpdated(object sender, EventArgs e)
		{
            if (e is AtentisConnectorEventArgs)
            {
                var dr = e as AtentisConnectorEventArgs;
                var row = dr.WrapperOrderbookRow;
            }
		}

        private int m_SellHole = 0;
        private int m_BuyHole = 0;

        private List<WrapperOrderbook> m_HedjOrderbook = new List<WrapperOrderbook>();
        private void ProcessHedjStakan(List<WrapperOrderbook> orderbook)
        {
            lock (m_HedjOrderbook)
            {
                m_SellHole = -1;
                m_BuyHole = -1;
                m_BeforeSellVol = -1;
                m_BeforeBuyVol = -1;

                m_HedjBestBuy = -1;
                m_HedjBestSell = -1;

                m_HedjBestBuyBehindVolume = -1;
                m_HedjBestSellBehindVolume = -1;

                int buyIndex = 0;
                int sellIndex = 0;

                m_HedjOrderbook.Clear();
                var sortedOrderbook = orderbook.OrderBy(x => x.Price);

                foreach (var row in sortedOrderbook)
                    m_HedjOrderbook.Add(row);

                buyIndex = -1;
                sellIndex = -1;

                if (m_HedjOrderbook.Count > 10)
                {
                    for (int i = 0; i < m_HedjOrderbook.Count - 1; i++)
                    {
                        if (m_HedjOrderbook[i].BuySell == "B" && m_HedjOrderbook[i + 1].BuySell == "S")
                        {
                            buyIndex = i;
                            sellIndex = i + 1;
                        }
                    }
                    /*
                    buyIndex = m_HedjOrderbook.FindLastIndex(x => x.BuySell == "B");
                    sellIndex = m_HedjOrderbook.FindIndex(x => x.BuySell == "S");
                    */
                    if (buyIndex < 0 || sellIndex < 0)
                    {
                        if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("m_HedjOrderbook.Count = {0}", m_HedjOrderbook.Count)));
                        return;
                    }

                    int buyVol = 0;
                    //ищем лучшую цену покупки спота с учетом опорника
                    for (int i = buyIndex; i >= 0; i--)
                    {
                        var row = m_HedjOrderbook[i];
                        buyVol += row.Quantity;
                        if (m_HedjBestBuy < 0 && buyVol >= m_BotSettings.IntCurOpora)
                            m_HedjBestBuy = row.Price;
                        if (m_HedjBestBuyBehindVolume < 0 && buyVol >= m_BotSettings.IntBeforeHedj)
                            m_HedjBestBuyBehindVolume = row.Price;

                        if (m_LastHedjSellOrder.Price > 0)
                        {
                            if (m_LastHedjSellOrder.Price >= row.Price)
                                m_BeforeBuyVol = buyVol;
                        }
                        else
                            if (m_HedjBestBuy > 0 && m_HedjBestBuyBehindVolume > 0) break;

                    }

                    int sellVol = 0;
                    //ищем лучшую цену продажи спота с учетом опорника
                    for (int i = sellIndex; i < m_HedjOrderbook.Count - 1; i++)
                    {
                        var row = m_HedjOrderbook[i];
                        sellVol += row.Quantity;
                        if (m_HedjBestSell < 0 && sellVol >= m_BotSettings.IntCurOpora)
                            m_HedjBestSell = row.Price;
                        if (m_HedjBestSellBehindVolume < 0 && sellVol >= m_BotSettings.IntBeforeHedj)
                            m_HedjBestSellBehindVolume = row.Price;

                        if (m_LastHedjBuyOrder.Price > 0)
                        {
                            if (m_LastHedjBuyOrder.Price <= row.Price)
                                m_BeforeSellVol = sellVol;
                        }
                        else
                            if (m_HedjBestSell > 0 && m_HedjBestSellBehindVolume > 0) break;
                    }

                }
                else
                    if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("m_SellDisp = {0}, m_BuyDisp = {1}, hedjBestBuy = {2}, hedjBestSell = {3}, workBestBuy = {4}, workBestSell = {5}", m_SellDisp, m_BuyDisp, m_HedjBestBuy, m_HedjBestSell, m_WorkBestBuy, m_WorkBestSell)));
                if (m_LastHedjBuyOrder.Price > 0 && m_LastHedjBuyOrder.Price < m_HedjBestBuy)
                {
                    m_BuyHole = (int)Math.Round((Math.Abs(m_HedjBestBuy - m_LastHedjBuyOrder.Price) * (double)m_BotSettings.FloatKHedj));
                }
                if (m_LastHedjSellOrder.Price > 0 && m_LastHedjSellOrder.Price > m_HedjBestSell)
                {
                    m_SellHole = (int)Math.Round((Math.Abs(m_LastHedjSellOrder.Price - m_HedjBestSell) * (double)m_BotSettings.FloatKHedj));
                }
                if (m_WorkPingReply != null && m_HedjPingReply != null)
                    if (m_WorkPingReply.RoundtripTime < MAXPING && m_HedjPingReply.RoundtripTime < MAXPING)
                        TryProcessDisp();
            }
        }

        object locker = new object();
        private void TryProcessDisp()
        {
            lock (locker)
            {
                ProcessDisps(m_WorkBestBuy, m_WorkBestSell, m_HedjBestBuy, m_HedjBestSell);
            }
        }

		#endregion Обработка стакана хеджера

		#region Расчет раздвижек
        private bool HaveMoneyForHedj(bool bsBool)
        {
            //Если продажа 'S'
            if (bsBool)
            {
                return (m_HedjCurPos >= 2*(int)m_BotSettings.FloatKHedj / m_BotSettings.HedjSecurity.LotSize * m_NextSellVol);
            }
            //Если покупка 'B'
            else
            {
                return (m_WorkCurPos >= 2 * m_NextBuyVol * m_BotSettings.WorkSecurity.SellDeposit && Math.Abs(m_MinPos - m_HedjConCount) > 2 * m_NextBuyVol*m_BotSettings.FloatKHedj/m_BotSettings.HedjSecurity.LotSize);
            }
        }

		private int m_SellDisp = 0;
		private int m_BuyDisp = 0;
		private void ProcessDisps(double workBestBuy, double workBestSell, double hedjBestBuy, double hedjBestSell)
		{

                m_CanDrawFace = false;
                if (hedjBestBuy < 0 || hedjBestSell < 0 || workBestBuy < 0 || workBestSell < 0)
                    return;

                m_SellDisp = (int)(Math.Round(workBestSell) - Math.Round((hedjBestSell * (double)m_BotSettings.FloatKHedj)));
                m_BuyDisp = -(int)(Math.Round((hedjBestBuy * (double)m_BotSettings.FloatKHedj)) - Math.Round(workBestBuy));
                //if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("m_SellDisp = {0}, m_BuyDisp = {1}, hedjBestBuy = {2}, hedjBestSell = {3}, workBestBuy = {4}, workBestSell = {5}", m_SellDisp, m_BuyDisp, hedjBestBuy, hedjBestSell, workBestBuy, workBestSell);

                // Проверим - можно ли продавать/покупать

                // Двусторонний
                if (curMode != RoboMode.rmMonitor)
                {
                    if (!m_MayInBuy) CheckChanceForSell(workBestBuy, workBestSell, hedjBestBuy, hedjBestSell);
                    if (!m_MayInSell) CheckChanceForBuy(workBestBuy, workBestSell, hedjBestBuy, hedjBestSell);
                }
                // Дохеджим рынок
                if (curMode == RoboMode.rmMonitor && (m_SellHedjTime || m_BuyHedjTime))
                {
                    if (!m_MayInBuy) CheckChanceForSell(workBestBuy, workBestSell, hedjBestBuy, hedjBestSell);
                    if (!m_MayInSell) CheckChanceForBuy(workBestBuy, workBestSell, hedjBestBuy, hedjBestSell);
                }
                m_CanDrawFace = true;

                /*
                this.SetPropertyThreadSafe(() => curSellDispLabel.Text, m_SellDisp.ToString());
                this.SetPropertyThreadSafe(() => curBuyDispLabel.Text, m_BuyDisp.ToString());
                */
		}

        #endregion Расчет раздвижек

		#region Торговля

        private OrderData m_LastWorkSellOrder = new OrderData();
        private OrderData m_LastWorkBuyOrder = new OrderData();
        private OrderData m_LastHedjSellOrder = new OrderData();
        private OrderData m_LastHedjBuyOrder = new OrderData();

		private bool m_MayInSell = false;
		private bool m_MayInBuy = false;

        private int m_LastDelWorkResult = 0;
        private int m_LastDelHedjResult = 0;

        private int m_LastWithdrawedAmount = 0;

        private void CheckChanceForSell(double workBestBuy, double workBestSell, double hedjBestBuy, double hedjBestSell)
		{
            if (!HaveMoneyForHedj(true))
            {
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Нет денег для продажи: {0}.", m_HedjCurPos)));
                return;
            }
			if (m_SellDisp > m_NextSellDisp && !m_MayInSell)
			{
				// можно продавать
                DoSell(workBestSell-1);
			}
            // Раздвижка ушла - снимаем фортс
            if (m_SellDisp <= m_NextSellDisp - 1 && m_MayInSell && (!m_SellHedjTime || m_IsSellHedjMadeFull))
            {
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Раздвижка ушла - снимаем фортс: m_SellDisp({0}) <= m_NextSellDisp-1({1}), m_LastDelResult = {2}", m_SellDisp, m_NextSellDisp - 1, m_LastDelWorkResult)));
                if ((m_LastDelWorkResult == 0 && aWorkCon.DelOrder(m_LastWorkSellOrder.OrderNo, out m_LastDelWorkResult, out m_LastWithdrawedAmount))||(m_LastDelWorkResult != 0 && m_ConCount == m_HedjConCount))
                {
                    if (m_LastWithdrawedAmount == m_LastWorkSellOrder.Amount)
                        ResetSell();
                    else
                        IsLastPartOfSell = true;
                }
            }

            // Встал объем впереди хеджера - переставляем спот как по-рынку
            if (m_CanSeeSpot&&((m_BeforeSellVol > m_BotSettings.IntBeforeHedj && m_HedjMode != HedjMode.hmVol) || (m_BeforeSellVol > 2 * m_BotSettings.IntBeforeHedj && m_HedjMode == HedjMode.hmVol)) && m_BuyHole > m_BotSettings.IntStakanHole && m_MayInSell && m_SellHedjTime)
            {
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Встал объем впереди хеджера - переставляем спот как по-рынку, m_LastDelResult = {0}", m_LastDelHedjResult)));
                if (m_LastDelHedjResult == 0 && aHedjCon.DelOrder(m_LastHedjBuyOrder.OrderNo, out m_LastDelHedjResult, out m_LastWithdrawedAmount))
                {
                    string extRef = string.Empty; //m_BotSettings.HedjLogin + "_" + m_BotSettings.HedjSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
                    string mktLimit = "L";

                    double price = hedjBestSell;
                    switch(m_HedjMode)
                    {
                        case HedjMode.hmAsMarket: price = hedjBestSell; break;
                        case HedjMode.hmDisp: price = hedjBestSell; break;
                        case HedjMode.hmSpred: price = hedjBestBuy; break;
                        case HedjMode.hmVol: price = (m_HedjBestBuyBehindVolume < 1) ? m_HedjBestSell : m_HedjBestBuyBehindVolume; break;
                        case HedjMode.hmAuto: 
                            {
                                int diff = m_SellDisp - m_NextSellDisp;
                                if (diff > THIRDLEVEL*m_BotSettings.FloatAutoStep) price = (m_HedjBestBuyBehindVolume < 1) ? m_HedjBestSell : m_HedjBestBuyBehindVolume;
                                else
                                    if (diff > SECONDLEVEL * m_BotSettings.FloatAutoStep) price = hedjBestBuy;
                                    else
                                        if (diff >= 0) price = hedjBestSell;
                                break;
                            }
                        default: break;
                    }

                    long outOrderNo = 0;
                    string outResMsg = string.Empty;
                    string secBoard = m_BotSettings.HedjSecurity.SecBoard;
                    string secCode = m_BotSettings.HedjSecurity.SecCode;
                    int res = 0;
                    int vol = (int)m_BotSettings.FloatKHedj / m_BotSettings.HedjSecurity.LotSize * m_SellHedjNeedVol + m_LastHedjBuyOrder.Amount;
                    //переставим все или неисполненную часть
                    if (m_LastWithdrawedAmount == m_LastHedjBuyOrder.Amount)
                        res = aHedjCon.AddOrder("B", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, vol, extRef, out outOrderNo, out outResMsg);
                    else
                        res = aHedjCon.AddOrder("B", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, vol - m_LastWithdrawedAmount, extRef, out outOrderNo, out outResMsg);
                    if (outOrderNo > 0)
                    {
                        m_SellHedjNeedVol = 0;
                        m_LastHedjBuyOrder = aHedjCon.OrderDatas.GetData(outOrderNo);
                        if (m_HedjMode == HedjMode.hmAsMarket) m_LastDelHedjResult = -100;
                    }
                }

            }
            // Делаем MoveOrder
            if (m_SellDisp > m_NextSellDisp && m_MayInSell && m_BeforeWorkSellVol > m_BotSettings.IntBeforeWork)
            {
                // можно продавать
                if (m_LastWorkSellOrder.MktLimit == "L" && m_LastWorkSellOrder.Price > workBestSell)
                {
                    string extRef = string.Empty; //m_BotSettings.WorkLogin + "_" + m_BotSettings.WorkSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
                    string extRef2 = string.Empty; //m_BotSettings.WorkLogin + "_" + m_BotSettings.WorkSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
                    long outOrderNo1 = 0;
                    long outOrderNo2 = 0;
                    string outResMsg = string.Empty;
                    int res = aWorkCon.MoveOrder(2, m_LastWorkSellOrder.OrderNo, workBestSell - 1, m_LastWorkSellOrder.Amount, extRef, 0, 0, 0, extRef2, out outOrderNo1, out outOrderNo2, outResMsg);
                    if (outOrderNo1 > 0)
                    {
                        m_LastWorkSellOrder = aWorkCon.OrderDatas.GetData(outOrderNo1);
                    }
                }
            }
		}

        private DateTime m_SellTryStartTime = DateTime.Now;
		private void DoSell(double price)
		{
            if (DateTime.Now < m_SellTryStartTime.AddSeconds(2))
            {
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Рано для продажи")));
                return;
            }
            m_MayInSell = true;
            string extRef = string.Empty; // m_BotSettings.WorkLogin + "_" + m_BotSettings.WorkSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
            string mktLimit = "L";
			int vol = m_NextSellVol;
			long outOrderNo = 0;
			string outResMsg = string.Empty;
			string secBoard = m_BotSettings.WorkSecurity.SecBoard;
			string secCode = m_BotSettings.WorkSecurity.SecCode;
            if (vol > 0 && price > 0)
            {
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("vol = {0}, curPos = {1}, max = {2}", vol, m_ConCount, m_BotSettings.IntMax)));
                int res = aWorkCon.AddOrder("S", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, vol, extRef, out outOrderNo, out outResMsg);
                if (outOrderNo > 0)
                {
                    m_LastWorkSellOrder = aWorkCon.OrderDatas.GetData(outOrderNo);
                }
                else
                {
                    if (res == -8)
                    {
                        m_SellTryStartTime = DateTime.Now;
                        AlarmMessages.ShowAlarm("Не удалось поставить заявку на продажу. Превышен лимит для данной учетной записи. Ждем 2 секунды.");
                    }
                    if (res < 0)
                    {
                        m_SellTryStartTime = DateTime.Now;
                        AlarmMessages.ShowAlarm("Не удалось поставить заявку на продажу. Код ошибки: " + res.ToString());
                    }
                    ResetSell();
                }
            }
            else
                ResetSell();
        }

        private void hedjSellTimer_Tick(object sender, EventArgs e)
        {
            EnableHedjSellTimerSafe(false);
            SetHedjSellIntervalSafe(1);
            HedjLastSell(0);
        }

        private bool m_SellHedjTime = false;
        private bool m_IsSellHedjMadeFull = true;
        private int m_SellHedjNeedVol = 0;
        private bool m_CanSeeSpot = false;
		private void HedjLastSell(int vol)
		{
//#error не хеджит цуко!!!
            m_SellHedjNeedVol += vol;
            if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Новый объем на дохедж продажи: {0}", vol)));

            if (m_SellHedjNeedVol == 0)
                return;
            if (!m_IsSellHedjMadeFull)
            {
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Ждем возможности дохеджить продажу")));
                EnableHedjSellTimerSafe(true);
                return;
            }

            string extRef = string.Empty; //m_BotSettings.HedjLogin + "_" + m_BotSettings.HedjSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
			string mktLimit = "L";
            while (m_LastWorkSellOrder.Price<1)
            {
                Thread.Sleep(1);
                Application.DoEvents();
            }
            double price = m_HedjBestSell;
            switch (m_HedjMode)
            {
                case HedjMode.hmAsMarket: price = m_HedjBestSell; break;
                case HedjMode.hmDisp: price = (m_LastWorkSellOrder.Price - m_NextSellDisp) / (double)m_BotSettings.FloatKHedj; break;
                case HedjMode.hmSpred: price = (m_LastWorkSellOrder.Price - m_NextSellDisp) / (double)m_BotSettings.FloatKHedj; break;
                case HedjMode.hmVol: price = (m_HedjBestBuyBehindVolume < 1) ? m_HedjBestSell : m_HedjBestBuyBehindVolume; break;
                case HedjMode.hmAuto:
                    {
                        int diff = m_SellDisp - m_NextSellDisp;
                        if (diff > THIRDLEVEL * m_BotSettings.FloatAutoStep) price = (m_HedjBestBuyBehindVolume < 1) ? m_HedjBestSell : m_HedjBestBuyBehindVolume;
                        else
                            if (diff > SECONDLEVEL * m_BotSettings.FloatAutoStep) price = price = (m_LastWorkSellOrder.Price - m_NextSellDisp) / (double)m_BotSettings.FloatKHedj;
                            else
                                if (diff >= 0) price = m_HedjBestSell;

                        break;
                    }
                default: break;
            }

			long outOrderNo = 0;
			string outResMsg = string.Empty;
			string secBoard = m_BotSettings.HedjSecurity.SecBoard;
			string secCode = m_BotSettings.HedjSecurity.SecCode;
            int realVol = (int)m_BotSettings.FloatKHedj / m_BotSettings.HedjSecurity.LotSize * m_SellHedjNeedVol;
            m_CanSeeSpot = false;
            int res = aHedjCon.AddOrder("B", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, realVol, extRef, out outOrderNo, out outResMsg);
			if (outOrderNo > 0)
			{
				m_LastHedjBuyOrder = aHedjCon.OrderDatas.GetData(outOrderNo);
                m_SellHedjTime = true;
                m_LastDelWorkResult = 0;
                m_LastDelHedjResult = 0;
                m_BeforeSellVol = 0;
                m_IsSellHedjMadeFull = false;
                m_SellHedjNeedVol = 0;
                m_CanSeeSpot = true;
			}
            else
            {
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Не удалось поставить ордер продажи, пробуем повторить")));
                SetHedjSellIntervalSafe(2000);
                EnableHedjSellTimerSafe(true);
                return;
            }
		}

        private void CheckChanceForBuy(double workBestBuy, double workBestSell, double hedjBestBuy, double hedjBestSell)
		{
            if (!HaveMoneyForHedj(false))
            {
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Нет денег для покупки: {0}.",m_WorkCurPos)));
                return;
            }
            if (m_BuyDisp < m_NextBuyDisp && !m_MayInBuy)
			{
				// можно покупать
                DoBuy(workBestBuy+1);
			}
            // Раздвижка ушла - снимаем фортс
            if (m_BuyDisp >= m_NextBuyDisp + 1 && m_MayInBuy && (!m_BuyHedjTime || m_IsBuyHedjMadeFull))
            {
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Раздвижка ушла - снимаем фортс: m_BuyDisp({0}) >= m_NextBuyDisp+1({1}), m_LastDelResult = {2}", m_BuyDisp, m_NextBuyDisp + 1, m_LastDelWorkResult)));
                if ((m_LastDelWorkResult == 0 && aWorkCon.DelOrder(m_LastWorkBuyOrder.OrderNo, out m_LastDelWorkResult, out m_LastWithdrawedAmount)) || (m_LastDelWorkResult != 0 && m_ConCount == m_HedjConCount))
                {
                    if (m_LastWithdrawedAmount == m_LastWorkBuyOrder.Amount)
                        ResetBuy();
                    else
                        IsLastPartOfBuy = true;
                }
            }
            // Пришел объем больше чем объем впереди хеджера - переставляем спот как по-рынку
            if (m_CanSeeSpot&&((m_BeforeBuyVol > m_BotSettings.IntBeforeHedj && (m_HedjMode != HedjMode.hmVol)) || ((m_BeforeBuyVol > 2 * m_BotSettings.IntBeforeHedj && (m_HedjMode == HedjMode.hmVol)))) && m_SellHole > m_BotSettings.IntStakanHole && m_MayInBuy && m_BuyHedjTime)
            {
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Пришел объем больше чем объем впереди хеджера - переставляем спот как по-рынку, m_LastDelResult = {0}", m_LastDelHedjResult)));
                if (m_LastDelHedjResult == 0 && aHedjCon.DelOrder(m_LastHedjSellOrder.OrderNo, out m_LastDelHedjResult, out m_LastWithdrawedAmount))
                {
                    string extRef = string.Empty; //m_BotSettings.HedjLogin + "_" + m_BotSettings.HedjSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
                    string mktLimit = "L";
                    double price = hedjBestBuy;
                    switch (m_HedjMode)
                    {
                        case HedjMode.hmAsMarket: price = hedjBestBuy; break;
                        case HedjMode.hmDisp: price = hedjBestBuy; break;
                        case HedjMode.hmSpred: price = hedjBestSell; break;
                        case HedjMode.hmVol: price = (m_HedjBestSellBehindVolume < 1) ? hedjBestBuy : m_HedjBestSellBehindVolume; break;
                        case HedjMode.hmAuto:
                            {
                                var diff = m_NextBuyDisp - m_BuyDisp;
                                if (diff > THIRDLEVEL * m_BotSettings.FloatAutoStep) price = (m_HedjBestSellBehindVolume < 1) ? hedjBestBuy : m_HedjBestSellBehindVolume;
                                else
                                    if (diff > SECONDLEVEL * m_BotSettings.FloatAutoStep) price = hedjBestSell;
                                    else
                                        if (diff >= 0) price = hedjBestBuy;

                                break;
                            }
                        default: break;
                    }

                    long outOrderNo = 0;
                    string outResMsg = string.Empty;
                    string secBoard = m_BotSettings.HedjSecurity.SecBoard;
                    string secCode = m_BotSettings.HedjSecurity.SecCode;
                    int res = 0;
                    //переставим все или неисполненную часть
                    int vol = (int)m_BotSettings.FloatKHedj / m_BotSettings.HedjSecurity.LotSize * m_BuyHedjNeedVol + m_LastHedjSellOrder.Amount;
                    if (m_LastWithdrawedAmount == m_LastHedjSellOrder.Amount)
                        res = aHedjCon.AddOrder("S", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, vol, extRef, out outOrderNo, out outResMsg);
                    else
                        res = aHedjCon.AddOrder("S", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, vol - m_LastWithdrawedAmount, extRef, out outOrderNo, out outResMsg);
                    if (outOrderNo > 0)
                    {
                        m_BuyHedjNeedVol = 0;
                        m_LastHedjSellOrder = aHedjCon.OrderDatas.GetData(outOrderNo);
                        if (m_HedjMode == HedjMode.hmAsMarket) m_LastDelHedjResult = -100;
                    }
                }

            }
            // Делаем MoveOrder
            if (m_BuyDisp < m_NextBuyDisp && m_MayInBuy && m_BeforeWorkBuyVol > m_BotSettings.IntBeforeWork)
            {
                // можно продавать
                if (m_LastWorkBuyOrder.MktLimit == "L" && m_LastWorkBuyOrder.Price < workBestBuy)
                {
                    string extRef = string.Empty; //m_BotSettings.WorkLogin + "_" + m_BotSettings.WorkSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
                    string extRef2 = string.Empty; //m_BotSettings.WorkLogin + "_" + m_BotSettings.WorkSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
                    long outOrderNo1 = 0;
                    long outOrderNo2 = 0;
                    string outResMsg = string.Empty;
                    int res = aWorkCon.MoveOrder(2, m_LastWorkBuyOrder.OrderNo, workBestBuy + 1, m_LastWorkBuyOrder.Amount, extRef, 0, 0, 0, extRef2, out outOrderNo1, out outOrderNo2, outResMsg);
                    if (outOrderNo1 > 0)
                    {
                        m_LastWorkBuyOrder = aWorkCon.OrderDatas.GetData(outOrderNo1);
                    }
                }
            }
		}

        private DateTime m_BuyTryStartTime = DateTime.Now;
		private void DoBuy(double price)
		{
            if (DateTime.Now < m_BuyTryStartTime.AddSeconds(2))
            {
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Рано для покупки")));
                return;
            }
            m_MayInBuy = true;
            string extRef = string.Empty; // m_BotSettings.WorkLogin + "_" + m_BotSettings.WorkSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
            string mktLimit = "L";
            int vol = m_NextBuyVol;
            long outOrderNo = 0;
            string outResMsg = string.Empty;
            string secBoard = m_BotSettings.WorkSecurity.SecBoard;
            string secCode = m_BotSettings.WorkSecurity.SecCode;
            if (vol > 0 && price > 0)
            {
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("vol = {0}, curPos = {1}, max = {2}", vol, m_ConCount, m_BotSettings.IntMax)));
                int res = aWorkCon.AddOrder("B", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, vol, extRef, out outOrderNo, out outResMsg);
                if (outOrderNo > 0)
                {
                    m_LastWorkBuyOrder = aWorkCon.OrderDatas.GetData(outOrderNo);
                }
                else
                {
                    if (res == -8)
                    {
                        m_BuyTryStartTime = DateTime.Now;
                        AlarmMessages.ShowAlarm("Не удалось поставить заявку на покупку. Превышен лимит для данной учетной записи. Ждем 2 секунды.");
                    }
                    if (res < 0)
                    {
                        m_BuyTryStartTime = DateTime.Now;
                        AlarmMessages.ShowAlarm("Не удалось поставить заявку на покупку. Код ошибки: " + res.ToString());
                    }
                    ResetBuy();
                }
            }
            else
                ResetBuy();
		}

        private void hedjBuyTimer_Tick(object sender, EventArgs e)
        {
            EnableHedjBuyTimerSafe(false);
            SetHedjBuyIntervalSafe(1);
            HedjLastBuy(0);
        }

        private bool m_IsBuyHedjMadeFull = true;
        private int m_BuyHedjNeedVol = 0;
        private bool m_BuyHedjTime = false;
        private void HedjLastBuy(int vol)
        {
            m_BuyHedjNeedVol += vol;
            if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Новый объем на дохедж покупки: {0}", vol)));

            if (m_BuyHedjNeedVol == 0)
                return;
            if (!m_IsBuyHedjMadeFull)
            {
                if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Ждем возможности дохеджить покупку.")));
                EnableHedjBuyTimerSafe(true);
                return;
            }

            string extRef = string.Empty; //m_BotSettings.HedjLogin + "_" + m_BotSettings.HedjSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
            string mktLimit = "L";
            while (m_LastWorkBuyOrder.Price < 1)
            {
                Thread.Sleep(1);
                Application.DoEvents();
            }

            double price = m_HedjBestBuy;

            switch (m_HedjMode)
            {
                case HedjMode.hmAsMarket: price = m_HedjBestBuy; break;
                case HedjMode.hmDisp: price = (m_LastWorkBuyOrder.Price - m_NextBuyDisp) / (double)m_BotSettings.FloatKHedj; break;
                case HedjMode.hmSpred: price = (m_LastWorkBuyOrder.Price - m_NextBuyDisp) / (double)m_BotSettings.FloatKHedj; break;
                case HedjMode.hmVol: price = (m_HedjBestSellBehindVolume < 1) ? m_HedjBestBuy : m_HedjBestSellBehindVolume; break;
                case HedjMode.hmAuto:
                    {
                        var diff = m_NextBuyDisp - m_BuyDisp;
                        if (diff > THIRDLEVEL * m_BotSettings.FloatAutoStep) price = (m_HedjBestSellBehindVolume < 1) ? m_HedjBestBuy : m_HedjBestSellBehindVolume;
                        else
                            if (diff > SECONDLEVEL * m_BotSettings.FloatAutoStep) price = (m_LastWorkBuyOrder.Price - m_NextBuyDisp) / (double)m_BotSettings.FloatKHedj;
                            else
                                if (diff >= 0) price = m_HedjBestBuy;

                        break;
                    }
                default: break;
            }

            long outOrderNo = 0;
            string outResMsg = string.Empty;
            string secBoard = m_BotSettings.HedjSecurity.SecBoard;
            string secCode = m_BotSettings.HedjSecurity.SecCode;
            int realVol = (int)m_BotSettings.FloatKHedj / m_BotSettings.HedjSecurity.LotSize * m_BuyHedjNeedVol;
            m_CanSeeSpot = false;
            int res = aHedjCon.AddOrder("S", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, realVol, extRef, out outOrderNo, out outResMsg);
            if (outOrderNo > 0)
            {
                m_LastHedjSellOrder = aHedjCon.OrderDatas.GetData(outOrderNo);
                m_BuyHedjTime = true;
                m_LastDelWorkResult = 0;
                m_LastDelHedjResult = 0;
                m_BeforeBuyVol = 0;
                m_IsBuyHedjMadeFull = false;
                m_BuyHedjNeedVol = 0;
                m_CanSeeSpot = true;
            }
            else
                {
                    if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("Не удалось поставить ордер покупки, пробуем повторить")));
                    SetHedjBuyIntervalSafe(2000);
                    EnableHedjBuyTimerSafe(true);
                }
        }

        #region работа с таймером

        /// Потокобезопасное обновление интервала таймера
        /// </summary>
        /// <param name="interval">Интервал в миллисекундах</param>
        private void SetHedjBuyIntervalSafe(int interval)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action<int>((s) => { SetHedjBuyInterval(s); }), interval);
            else
                SetHedjBuyInterval(interval);
        }

        /// <summary>
        /// Задает интервал таймера
        /// </summary>
        /// <param name="interval">Интервал в миллисекундах</param>
        private void SetHedjBuyInterval(int interval)
        {
            this.hedjBuyTimer.Interval = interval;
        }

        private void SetHedjSellIntervalSafe(int interval)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action<int>((s) => { SetHedjSellInterval(s); }), interval);
            else
                SetHedjSellInterval(interval);
        }

        /// <summary>
        /// Задает интервал таймера
        /// </summary>
        /// <param name="interval">Интервал в миллисекундах</param>
        private void SetHedjSellInterval(int interval)
        {
            this.hedjSellTimer.Interval = interval;
        }


        /// <summary>
        /// Потокобезопасная активация таймера
        /// </summary>
        /// <param name="Enabled">Состояние таймера</param>
        private void EnableHedjBuyTimerSafe(bool Enabled)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action<bool>((s) => { EnableHedjBuyTimer(s); }), Enabled);
            else EnableHedjBuyTimer(Enabled);
        }

        /// <summary>
        /// Активирует таймер
        /// </summary>
        /// <param name="Enabled">Состояние таймера</param>
        private void EnableHedjBuyTimer(bool Enabled)
        {
            this.hedjBuyTimer.Enabled = Enabled;
        }

        /// <summary>
        /// Потокобезопасная активация таймера
        /// </summary>
        /// <param name="Enabled">Состояние таймера</param>
        private void EnableHedjSellTimerSafe(bool Enabled)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action<bool>((s) => { EnableHedjSellTimer(s); }), Enabled);
            else EnableHedjSellTimer(Enabled);
        }

        /// <summary>
        /// Активирует таймер
        /// </summary>
        /// <param name="Enabled">Состояние таймера</param>
        private void EnableHedjSellTimer(bool Enabled)
        {
            this.hedjSellTimer.Enabled = Enabled;
        }


        #endregion работа с таймером

        #endregion Торговля

        #region Пакетник

        private int m_NextSellDisp = 0;
        private int m_NextBuyDisp = 0;
        private int m_NextSellVol = 0;
        private int m_NextBuyVol = 0;
        private const int MAXPING = 200;

        // Расчет следующих цен продажи и покупки
        private void PerformDisp()
        {
            GetConCount();

            if (m_BotSettings.IntAveraging == 0)
            {
                // раздвижки
                m_NextSellDisp = m_BotSettings.IntSellDisp;
                m_NextBuyDisp = m_BotSettings.IntBuyDisp;

                // рабочий объем
                if (m_ConCount == 0)
                {
                    if (Math.Abs(m_BotSettings.IntMax) > 0)
                    {
                        if (curMode == RoboMode.rmLimitTwoWay)
                        {
                            m_NextSellVol = m_NextBuyVol = m_BotSettings.IntCurWorkVol;
                        }
                        if (curMode == RoboMode.rmLimitFromSell)
                        {
                            m_NextSellVol = m_BotSettings.IntCurWorkVol;
                            m_NextBuyVol = 0;
                        }
                        if (curMode == RoboMode.rmLimitFromBuy)
                        {
                            m_NextSellVol = 0;
                            m_NextBuyVol = m_BotSettings.IntCurWorkVol;
                        }
                    }
                    else
                    {
                        m_NextBuyVol = 0;
                        m_NextSellVol = 0;
                    }
                }
                if (m_ConCount < 0)
                {
                    int y = Math.Abs(m_ConCount);
                    if (y < Math.Abs(m_BotSettings.IntMax))
                    {
                        int x = Math.Abs(Math.Abs(m_BotSettings.IntMax) - Math.Abs(m_ConCount));
                        if (x < m_BotSettings.IntCurWorkVol) m_NextSellVol = x;
                        else
                            m_NextSellVol = m_BotSettings.IntCurWorkVol;
                    }
                    else
                        m_NextSellVol = 0;
                }
                if (m_ConCount > 0)
                {
                    int x = Math.Abs(m_ConCount);
                    if (x < Math.Abs(m_BotSettings.IntMax2))
                    {
                        int y = Math.Abs(Math.Abs(m_BotSettings.IntMax2) - Math.Abs(m_ConCount));
                        if (y < m_BotSettings.IntCurWorkVol) m_NextBuyVol = y;
                        else
                            m_NextBuyVol = m_BotSettings.IntCurWorkVol;
                    }
                    else
                        m_NextBuyVol = 0;
                }
            }
            else
            {
                // раздвижки
                if (m_ConCount == 0)
                {

                    if (curMode == RoboMode.rmLimitTwoWay || curMode == RoboMode.rmMonitor)
                    {
                        m_NextSellDisp = m_BotSettings.IntSellDisp;
                        m_NextBuyDisp = m_BotSettings.IntBuyDisp;
                    }
                    if (curMode == RoboMode.rmLimitFromSell)
                    {
                        m_NextSellDisp = m_BotSettings.IntSellDisp;
                        m_NextBuyDisp = m_NextSellDisp - m_BotSettings.IntHotelka;
                    }
                    if (curMode == RoboMode.rmLimitFromBuy)
                    {
                        m_NextBuyDisp = m_BotSettings.IntBuyDisp;
                        m_NextSellDisp = m_NextBuyDisp + m_BotSettings.IntHotelka;
                    }

                }
                if (m_ConCount < 0)
                {
                    if (m_NextSellDisp > m_BotSettings.IntSellAllIn)
                    {
                        this.sellDispTextBox.Text = (m_BotSettings.IntSellDisp - 1).ToString();
                        AcceptSettings();
                    }
                    if (m_NextBuyDisp < m_BotSettings.IntSellAllOut)
                    {
                        this.sellDispTextBox.Text = (m_BotSettings.IntSellDisp + 1).ToString();
                        AcceptSettings();
                    }
                    m_NextSellDisp = m_BotSettings.IntSellDisp + Math.Abs(m_ConCount / m_BotSettings.IntPackage * m_BotSettings.IntAveraging);
                    m_NextBuyDisp = m_NextSellDisp - m_BotSettings.IntHotelka;
                }
                if (m_ConCount > 0)
                {
                    if (m_NextSellDisp > m_BotSettings.IntBuyAllOut)
                    {
                        this.buyDispTextBox.Text = (m_BotSettings.IntSellDisp - 1).ToString();
                        AcceptSettings();
                    }
                    if (m_NextBuyDisp < m_BotSettings.IntBuyAllIn)
                    {
                        this.buyDispTextBox.Text = (m_BotSettings.IntBuyDisp + 1).ToString();
                        AcceptSettings();
                    }
                    m_NextBuyDisp = m_BotSettings.IntBuyDisp - Math.Abs(m_ConCount / m_BotSettings.IntPackage2 * m_BotSettings.IntAveraging2);
                    m_NextSellDisp = m_NextBuyDisp + m_BotSettings.IntHotelka2;
                }

                if (m_ConCount == 0)
                {
                    // рабочие объемы
                    var curPack = Math.Abs(m_ConCount / m_BotSettings.IntPackage);
                    var nextPack = (curPack + 1) * m_BotSettings.IntPackage;

                    if (Math.Abs(m_BotSettings.IntMax) > 0)
                    {
                        if (curMode == RoboMode.rmLimitTwoWay)
                        {
                            m_NextSellVol = m_NextBuyVol = m_BotSettings.IntCurWorkVol;
                        }
                        if (curMode == RoboMode.rmLimitFromSell)
                        {
                            m_NextSellVol = m_BotSettings.IntCurWorkVol;
                            m_NextBuyVol = 0;
                        }
                        if (curMode == RoboMode.rmLimitFromBuy)
                        {
                            m_NextSellVol = 0;
                            m_NextBuyVol = m_BotSettings.IntCurWorkVol;
                        }
                    }
                    else
                    {
                        m_NextBuyVol = 0;
                        m_NextSellVol = 0;
                    }
                }
                if (m_ConCount < 0)
                {
                    // рабочие объемы
                    var curPack = Math.Abs(m_ConCount / m_BotSettings.IntPackage);
                    var nextPack = (curPack + 1) * m_BotSettings.IntPackage;

                    int x = Math.Abs(Math.Abs(nextPack) - Math.Abs(m_ConCount));
                    int q = Math.Abs(Math.Abs(m_BotSettings.IntMax) - Math.Abs(m_ConCount));
                    if (Math.Abs(m_ConCount) >= Math.Abs(m_BotSettings.IntMax)) m_NextSellVol = 0;
                    else
                        if (x <= m_BotSettings.IntCurWorkVol) m_NextSellVol = x;
                        else
                            if (q <= m_BotSettings.IntCurWorkVol) m_NextSellVol = q;
                            else
                                m_NextSellVol = m_BotSettings.IntCurWorkVol;

                    int y = Math.Abs(Math.Abs(curPack) - Math.Abs(m_ConCount));
                    int t = Math.Abs(m_ConCount);
                    if (Math.Abs(curPack) < Math.Abs(m_ConCount) && y <= m_BotSettings.IntCurWorkVol) m_NextBuyVol = y;
                    else
                        if (t <= m_BotSettings.IntCurWorkVol) m_NextBuyVol = t;
                        else
                            m_NextBuyVol = m_BotSettings.IntCurWorkVol;
                }
                if (m_ConCount > 0)
                {
                    // рабочие объемы
                    var curPack = Math.Abs(m_ConCount / m_BotSettings.IntPackage2);
                    var nextPack = (curPack + 1) * m_BotSettings.IntPackage2;

                    int x = Math.Abs(Math.Abs(m_ConCount) - Math.Abs(curPack));
                    int q = Math.Abs(m_ConCount);
                    if (Math.Abs(curPack) < Math.Abs(m_ConCount) && x <= m_BotSettings.IntCurWorkVol) m_NextSellVol = x;
                    else
                        if (q <= m_BotSettings.IntCurWorkVol) m_NextSellVol = q;
                        else
                            m_NextSellVol = m_BotSettings.IntCurWorkVol;

                    int y = Math.Abs(Math.Abs(nextPack) - Math.Abs(m_ConCount));
                    int t = Math.Abs(Math.Abs(m_BotSettings.IntMax2) - Math.Abs(m_ConCount));
                    if (Math.Abs(m_ConCount) >= Math.Abs(m_BotSettings.IntMax2)) m_NextBuyVol = 0;
                    else
                        if (y <= m_BotSettings.IntCurWorkVol) m_NextBuyVol = y;
                        else
                            if (t <= m_BotSettings.IntCurWorkVol) m_NextBuyVol = t;
                            else
                                m_NextBuyVol = m_BotSettings.IntCurWorkVol;
                }
            }
        }
        #endregion Пакетник

        #region Отображение данных на форме

        private bool m_CanDrawFace = false;

        private void dispTimer_Tick(object sender, EventArgs e)
		{
            CheckClearing();
            if (m_CanDrawFace) DrawFace();
		}

        private void nextBuyDispNumericUpDown_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Up)
                this.buyDispTextBox.Text = (m_BotSettings.IntBuyDisp + 1).ToString();
            if (e.KeyData == Keys.Down)
                this.buyDispTextBox.Text = (m_BotSettings.IntBuyDisp - 1).ToString();
            AcceptSettings();
            /*
            if (e.KeyData == Keys.Up)
                m_BotSettings.BuyDisp = (m_BotSettings.IntBuyDisp + 1).ToString();
            if (e.KeyData == Keys.Down)
                m_BotSettings.BuyDisp = (m_BotSettings.IntBuyDisp - 1).ToString();
            */
        }

        private void nextSellDispNumericUpDown_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Up)
                this.sellDispTextBox.Text = (m_BotSettings.IntSellDisp + 1).ToString();
            if (e.KeyData == Keys.Down)
                this.sellDispTextBox.Text = (m_BotSettings.IntSellDisp - 1).ToString();
            AcceptSettings();
            /*
            if (e.KeyData == Keys.Up)
                m_BotSettings.SellDisp = (m_BotSettings.IntSellDisp + 1).ToString();
            if (e.KeyData == Keys.Down)
                m_BotSettings.SellDisp = (m_BotSettings.IntSellDisp - 1).ToString();
            */
        }

        private int m_PrevTradingMode = -1;
        private void CheckClearing()
        {
            DateTime kBeginTime = DateTime.Parse("13:59:57");
            DateTime kEndTime = DateTime.Parse("14:03:01");
            DateTime eowTime = DateTime.Parse("18:44:50");
            DateTime tNow = DateTime.Now;

            if (m_PrevTradingMode < 0 &&
                tradingModeComboBox.SelectedIndex > 0 &&
                kBeginTime.TimeOfDay.Hours == tNow.TimeOfDay.Hours &&
                kBeginTime.TimeOfDay.Minutes == tNow.TimeOfDay.Minutes &&
                kBeginTime.TimeOfDay.Seconds == tNow.TimeOfDay.Seconds)
            {
                m_PrevTradingMode = tradingModeComboBox.SelectedIndex;
                ResetBot();
            }

            if (m_PrevTradingMode > 0 &&
                kEndTime.TimeOfDay.Hours == tNow.TimeOfDay.Hours &&
                kEndTime.TimeOfDay.Minutes == tNow.TimeOfDay.Minutes &&
                kEndTime.TimeOfDay.Seconds == tNow.TimeOfDay.Seconds)
            {
                tradingModeComboBox.SelectedIndex = m_PrevTradingMode;
                m_PrevTradingMode = -1;
            }

            if (m_PrevTradingMode < 0 &&
                tradingModeComboBox.SelectedIndex > 0 &&
                eowTime.TimeOfDay.Hours == tNow.TimeOfDay.Hours &&
                eowTime.TimeOfDay.Minutes == tNow.TimeOfDay.Minutes &&
                eowTime.TimeOfDay.Seconds == tNow.TimeOfDay.Seconds)
            {
                m_PrevTradingMode = tradingModeComboBox.SelectedIndex;
                ResetBot();
            }
        }

        private void DrawFace()
        {

            PerformDisp();

            if (m_WorkPingReply != null && m_HedjPingReply != null)
                this.Text = m_BotSettings.WorkLogin + " " + m_BotSettings.WorkSecurity.ShortName + " [" + m_WorkPingReply.RoundtripTime + "][" + m_HedjPingReply.RoundtripTime + "]";
            /*
            this.nextSellDispLabel.Text = m_WorkBestSell.ToString();//m_NextSellDisp.ToString();
            this.nextBuyDispLabel.Text = m_WorkBestBuy.ToString();//m_NextBuyDisp.ToString();
            */
            this.nextSellDispNumericUpDown.Value = m_NextSellDisp;
            this.nextBuyDispNumericUpDown.Value = m_NextBuyDisp;

            if (m_HedjBestBuy < 0 || m_HedjBestSell < 0 || m_WorkBestBuy < 0 || m_WorkBestSell < 0)
            {
                this.curSellDispLabel.Text = this.curBuyDispLabel.Text = "Error";
            }
            else
            {
                /*
                this.curSellDispLabel.Text = m_HedjBestSell.ToString();// m_SellDisp.ToString();
                this.curBuyDispLabel.Text = m_HedjBestBuy.ToString();// m_BuyDisp.ToString();
                */
                this.curSellDispLabel.Text = m_SellDisp.ToString();
                this.curBuyDispLabel.Text = m_BuyDisp.ToString();
            }

            this.conCountLabel.Text = m_ConCount.ToString();
            //this.conCountLabel.Text = m_WorkCurPos.ToString();
            //this.conCountLabel.Text = m_HedjBestBuyBehindVolume.ToString();
            if (m_ConCount == 0)
                this.conCountLabel.BackColor = Color.Blue;
            if (m_ConCount > 0)
                this.conCountLabel.BackColor = Color.LightGreen;
            if (m_ConCount < 0)
                this.conCountLabel.BackColor = Color.LightPink;

            this.hedjPosLabel.Text = m_HedjConCount.ToString();
            //this.hedjPosLabel.Text = m_HedjBestSellBehindVolume.ToString();
            //this.hedjPosLabel.Text = m_HedjCurPos.ToString();
            //this.hedjPosLabel.Text = m_BotSettings.WorkSecurity.SellDeposit.ToString();
            if (m_HedjConCount == 0)
                this.hedjPosLabel.BackColor = Color.Aqua;
            if (m_HedjConCount > 0)
                this.hedjPosLabel.BackColor = Color.LightGreen;
            if (m_HedjConCount < 0)
                this.hedjPosLabel.BackColor = Color.LightPink;

            if (!m_MayInBuy && !m_MayInSell || curMode == RoboMode.rmMonitor)
                mainPanel.BackColor = m_DefCol;
            else
                if (m_MayInSell)
                    mainPanel.BackColor = Color.Red;
                else
                    if (m_MayInBuy)
                        mainPanel.BackColor = Color.Green;
        }

		#endregion Отображение данных на форме

        #region Обработка клавиш
        private void mainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Escape)
            {
                ResetBot();
            }
            if (e.KeyData == Keys.F1)
                tradingModeComboBox.SelectedIndex = 1;
            if (e.KeyData == Keys.F2)
                tradingModeComboBox.SelectedIndex = 2;
            if (e.KeyData == Keys.F3)
                tradingModeComboBox.SelectedIndex = 3;
        }

        private void ResetBot()
        {

            if (m_MayInSell && !m_SellHedjTime)
            {
                aWorkCon.DelOrder(m_LastWorkSellOrder.OrderNo, out m_LastDelWorkResult, out m_LastWithdrawedAmount);
            }
            if (m_MayInBuy && !m_BuyHedjTime)
            {
                aWorkCon.DelOrder(m_LastWorkBuyOrder.OrderNo, out m_LastDelWorkResult, out m_LastWithdrawedAmount);
            }
            tradingModeComboBox.SelectedIndex = 0;
            ResetSell();
            ResetBuy();
        }
        #endregion Обработка клавиш

        #region Пинг
        private System.Net.NetworkInformation.Ping m_WorkPing = new System.Net.NetworkInformation.Ping();
        private System.Net.NetworkInformation.Ping m_HedjPing = new System.Net.NetworkInformation.Ping();
        private System.Net.NetworkInformation.PingReply m_WorkPingReply;
        private System.Net.NetworkInformation.PingReply m_HedjPingReply;
        private void pingTimer_Tick(object sender, EventArgs e)
        {
            (new System.Threading.Thread(delegate()
            {
                try
                {
                    if (!string.IsNullOrEmpty(m_BotSettings.WorkServ))
                        m_WorkPingReply = m_WorkPing.Send(m_BotSettings.WorkServ);
                    if (!string.IsNullOrEmpty(m_BotSettings.HedjServ))
                        m_HedjPingReply = m_HedjPing.Send(m_BotSettings.HedjServ);
                }
                catch
                { }
            })).Start();
        }
        #endregion Пинг

        #region Проверка ключа
        private bool CheckKey()
        {
            string str = string.Empty;
            string wl = m_BotSettings.WorkLogin.ToUpper();
            str += wl;
            DateTime d = DateTime.Now;
            str += d.Year;
            str = CryptoKeys.CalculateMD5Hash(str);
            string sYear = m_BotSettings.WorkSecurity.Time.Year.ToString();
            str += sYear;
            str = CryptoKeys.CalculateMD5Hash(str);
            //if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("KEY::: workLogin = {0}, system.Year == {1}, servYear = {2}, hash = {3}, key = {4}", wl, d.Year, sYear, str, m_BotSettings.Key)));
            if (aWorkCon != null) aWorkCon.RQS_evhLogLine(null, new TableEventArgs(string.Format("KEY:::  workLogin = {0}, system.Year == {1}, servYear = {2} :" + (str == m_BotSettings.Key).ToString(), wl, d.Year, sYear)));
            return str == m_BotSettings.Key;
        }
        #endregion Проверка ключа

        #region Выбор режима хеджирования
        private HedjMode m_HedjMode = HedjMode.hmSpred;
        private void hedjModeComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (hedjModeComboBox.SelectedIndex)
            {
                case 0: m_HedjMode = HedjMode.hmAsMarket; if (m_BotSettings!= null) m_BotSettings.HedjMode = 0; break;
                case 1: m_HedjMode = HedjMode.hmDisp; if (m_BotSettings != null) m_BotSettings.HedjMode = 1; break;
                case 2: m_HedjMode = HedjMode.hmSpred; if (m_BotSettings != null) m_BotSettings.HedjMode = 2; break;
                case 3: m_HedjMode = HedjMode.hmVol; if (m_BotSettings != null) m_BotSettings.HedjMode = 3; break;
                case 4: m_HedjMode = HedjMode.hmAuto; if (m_BotSettings != null) m_BotSettings.HedjMode = 4; break;
				default:
					break;
            }
        }
        #endregion Выбор режима хеджирования


//todo
        /*
         Функция олин и олаут *
         Разные пакеты и хотелки *
         Единое подключение для ботов в рамках одного логина.
         Три бота в одном (2 фьюча против спота и фьюч против фьюча)
         */

    }
}
